How to sort an array in java without using the sort method
How to sort an array in java without using the sort method:-
You can find so many different sorting algorithms on the internet, but if you want to fix your own solution you can do the following changes in your code:
Instead of:
orderedNums[greater]=tenNums[indexL];
you need to do this:
while (orderedNums[greater] == tenNums[indexL]) {
greater++;
}
orderedNums[greater] = tenNums[indexL];
This code basically checks if that particular index is occupied by a similar number, then it will try to find the next free index.
Note: Since the default value in your sorted array elements is 0, you need to make sure 0 is not in your list. otherwise, you need to initiate your sorted array with an especial number that you sure is not in your list e.g: Integer.MAX_VALUE
Here is one simple solution
public static void main(String[] args) {
//Without using Arrays.sort function
int i;
int nos[] = {12,9,-4,-1,3,10,34,12,11};
System.out.print("Values before sorting: \n");
for(i = 0; i < nos.length; i++)
System.out.println( nos[i]+" ");
sort(nos, nos.length);
System.out.print("Values after sorting: \n");
for(i = 0; i <nos.length; i++){
System.out.println(nos[i]+" ");
}
}
private static void sort(int nos[], int n) {
for (int i = 1; i < n; i++){
int j = i;
int B = nos[i];
while ((j > 0) && (nos[j-1] > B)){
nos[j] = nos[j-1];
j--;
}
nos[j] = B;
}
}
And the output is:
Values before sorting:
12
9
-4
-1
3
10
34
12
11
Values after sorting:
-4
-1
3
9
10
11
12
12
34