For sorting in the order of ascending or descending, we have one of the most popular sorting technique is bubble sort.
What is bubble sort – repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted.
public class SortingArr { public static void main(String[] args) { int[] numbers = {112, 43, 10, 14, 87, 76}; int n = numbers.length; //Bubble sort System.out.println("length: " + n); for (int i = 0; i < n-1 ; i++) { for (int j = 0; j < n-i-1 ; j++) { /* For ascending order */ if (numbers[j] > numbers[j+1]) { int temp = numbers[j]; numbers[j] = numbers[j+1]; numbers[j+1] = temp; } } } for(int i=0; i<n ; i++) System.out.println(numbers[i]); } }
If string, then sorting is as follows –
String[] names = {"sunil", "kumar", "patro"}; int c = names.length; for (int i = 0; i < c-1 ; i++) { for (int j = 0; j < c-i-1 ; j++) { /* For ascending order */ if (names[j].compareTo(names[j+1])>0) { String temp = names[j]; names[j] = names[j+1]; names[j+1] = temp; } } } for (int i = 0; i < c ; i++) System.out.println(names[i]);