Java Program Implement and test a bubble sort To sort n numb

Java Program:

Implement and test a bubble sort. To sort n numbers, make n-1 passes. On each pass, compare every pair of adjacent numbers. If any pair is not in ascending order, switch the pair. On the first pass, start from the first element (compare the first with the second, the second with the third, and so on). On the second pass, again start from the first element but stop your compares one slot from the end of the array. In each successive pass, stop one slot before the stopping point of the previous pass. Use your bubble sort to sort 100, 23, 15, 23, 7, 23, 2, 311, 5, 8 and 3. Display the sorted numbers.

Solution

import java.util.Scanner;

class BubbleSort
{
public static void main(String []args)
{
int n, c, d, swap;
Scanner in = new Scanner(System.in); System.out.println(\"Input number of integers to sort\");
n = in.nextInt();   
int array[] = new int[n]; System.out.println(\"Enter \" + n + \" integers\");
for (c = 0; c < n; c++) array[c] = in.nextInt(); for (c = 0; c < ( n - 1 );
c++)
{
for (d = 0; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For descending order use < */
{
swap = array[d];
array[d] = array[d+1]; array[d+1] = swap;
}
}
}

System.out.println(\"Sorted list of numbers\");
for (c = 0; c < n; c++)

System.out.println(array[c]);
}
}

Java Program: Implement and test a bubble sort. To sort n numbers, make n-1 passes. On each pass, compare every pair of adjacent numbers. If any pair is not in

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site