How sorting is used in java?
How sorting is used in java?
This example shows how the array is sorted using bubble sort.
In bubble sort basically array is traverse from first to the array_length-1 position.
int n = Array.length;
int temp = 0;
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(Array[j-1] > Array[j]){
temp = Array[j-1];
Array[j-1] = Array[j];
Array[j] = temp;
Compare the value at array[0] and array[1]
if array[0]>array[1] swap the value
and than compare array[1] and array[2]
if array[1]> array[2] swap the value
at last compare array[n-1] and array[n] the largest element come at the last posistion.
package Example;
public class Bubblesort {
public static void main(String[] args) {
//create an int array we want to sort using bubble sort algorithm
int Array[] = new int[]{3,9,84,10,45,2,};
//print array before sorting using bubble sort algorithm
System.out.println("Array Before Bubble Sort");
for(int i=0; i < Array.length; i++){
System.out.print(Array[i] + " ");
}
bubbleSort(Array);
System.out.println("");
System.out.println("Array After Bubble Sort");
for(int i=0; i < Array.length; i++){
System.out.print(Array[i] + " ");
}
}
private static void bubbleSort(int[]Array) {
int n = Array.length;
int temp = 0;
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(Array[j-1] > Array[j]){
temp = Array[j-1];
Array[j-1] = Array[j];
Array[j] = temp;
}
}
}
}
}
Array Before Bubble Sort
3 9 84 10 45 2
Array After Bubble Sort
2 3 9 10 45 84