Many predefined functions make your work easier but sometimes we want to do without using them.
Procedure:
To sort the array without using the sort algorithm, take the array of strings and sort the array based on the first string. Once you have done, then take the array of strings again and sort it based on the second character. Then again based on the third character and so on until you reach the length of the largest string.
Example:
This example will sort array elements in ascending and descending order both without using array sort method;
int a[]={6,2,5,1};
System.out.println(Arrays.toString(a));
int temp;
for(int i=0;i<a.length-1;i++){
for(int j=0;j<a.length-1;j++){
if(a[j] > a[j+1]){ // use < for Descending order
temp = a[j+1];
a[j+1] = a[j];
a[j]=temp;
}
}
}
System.out.println(Arrays.toString(a));
Output:
[6, 2, 5, 1] // output for ascending order
[1, 2, 5, 6] //output for descending order
Second Example:
In this example we sort the array by using bubble sort.
public static void main(String[] args) {
int[] arr = new int[] { 6, 8, 7, 4, 312, 78, 54, 9, 12, 100, 89, 74 };
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
int tmp = 0;
if (arr[i] > arr[j]) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
}