Write a program to bubble-sort the following set of values in ascending order: 5,3,8,4,9,2,1,l2,98,16
Answers
public class BubbleSort
{
public static void main(String[] args)
{
int a[] = {5,3,8,4,9,2,1,12,98,16};
int l = a.length;
int i,j,k;
System.out.println("Given array is:");
for(i=0;i<10;i++)
{
System.out.print(a[i]+" ");
}
for (i=0;i<9;i++)
{
for(j=0;j<(9-i);j++)
{
if(a[j]>a[j+1])
{
k = a[j];
a[j] = a[j+1];
a[j+1] = k;
}
}
}
System.out.println();
System.out.println("Array sorted in ascending order is:");
for(i=0;i<10;i++)
{
System.out.print(a[i]+" ");
}
}
}
@vikramjeeth
Answer:
Here's a Python program to bubble-sort the given set of values in ascending order:
less
Copy code
values = [5, 3, 8, 4, 9, 2, 1, 12, 98, 16]
for i in range(len(values)):
for j in range(len(values)-1):
if values[j] > values[j+1]:
values[j], values[j+1] = values[j+1], values[j]
print("Sorted values in ascending order:")
print(values)
The program iterates over the list of values using nested loops. In each iteration of the outer loop, the program compares adjacent elements in the list using the inner loop. If the value on the left is greater than the value on the right, the program swaps their positions. This process repeats until the list is sorted in ascending order. The sorted list is then printed to the console.