Takkk Blog

Tak Takkk

RSS
people

How To Sort An Array In Descending Order in Java?

I am writing this post because i cannot find the code or idea to sort an Array without using Arrays class and its methods on the Internet. Here is methods that i wrote to sort an Array in a descending way. BTW, i write to methods to achieve this, one finds the maximum value in the array and returns the its index, the other one use first array and sort the Array.

public int getMaxArray(int[] a, int start){

int max = 0;

int index = 0;

for(int i = start; i<a.length;i++){

if(a[i]>max){

max = a[i];

index = i;

}

}

return index;

}

//The method that uses the first one to find the index of maximum element in the Array.

public int[] sorted(int[] a){

int temp = 0;

for(int i = 0;i<a.length;i++){

int maxIndex = getMaxArray(a, i);

temp = a[i];

a[i] = a[maxIndex];

a[maxIndex] = temp;

}

return a;

}

This is it. You can optimize the code, i think. Since i have just write to code and put it on the web with all of my pleasure, there might be some reductions in the code.

No Comments | Tags: , , ,