Jump to content
xisto Community
Sign in to follow this  
iGuest

Array Sorting Does anyone hava a decent JAVA method

Recommended Posts

Why don't you just use the builtin java sorting function in java.util package, Arrays.sort(int[] a), to do that?The builtin function use quick sort, which is much more effective than the method you described. Also because it's well published (it's here since Java 2), it's already heavily tested and sure will not have any bugs, rather than coded by yourself.~~ :)

here's an example of the java api Arrays.sort in use

import java.util.Arrays;public class MainClass {  public static void main(String[] a) {	int array[] = { 2, 5, -2, 6, -3 };	Arrays.sort(array);	for (int i : array) {	  System.out.println(i);	}  }}
CONSOLE

-3
-2
2
5
6

Edited by jc804 (see edit history)

Share this post


Link to post
Share on other sites

lets start with a bubble sort code in JAVA

public class BubbleSort{public static void main(String args[]){int array[] = new int[10];for (int i=0; i < array.length; i++){array[i] = (int)(java.lang.Math.random()*100);}bubbleSort(array);for (int i=0; i < array.length; i++){System.out.println("Val of array[" + i + "] = " +array[i] );}}public static void bubbleSort(int arr[]){  for (int i=0; i<arr.length; i++)  {  for (int j=0; j<arr.length-i; j++)  {   if(arr[j]>arr[j+1]){     int tmp =arr[j];     arr[j]=arr[j+1];     arr[j+1]=tmp;        }  }  }}}for each iteration of the inner loop the next highest value is bubbled to the last position of the remaining array;

Edited by Umar Shah (see edit history)

Share this post


Link to post
Share on other sites

Next I'll try to demonstrate a relatively simpler sort called Selection sort;

public class SelectionSort{public static void main(String args[]){int array[] = new int[10];for (int i=0; i < array.length; i++){array[i] = (int)(java.lang.Math.random()*100);}selectionSort(array);for (int i=0; i < array.length; i++){System.out.println("Val of array[" + i + "] = " +array[i] );}}public static void selectionSort(int arr[]){for (int i=0; i<arr.length; i++){for (int j=i+1; j<arr.length-1; j++){if(arr[i]>arr[j]){int tmp =arr[j];arr[i]=arr[j];arr[j]=tmp;}}}}}

in this example the inner loop just compares all the elements from position i to the end to find the mininmum one to be placed at position i,

the position determined by each iteration of outer loop.
Edited by Umar Shah (see edit history)

Share this post


Link to post
Share on other sites

Now in this example i'll demonstrate one of my favourite O(n^2) sorts.

This one is called insertion sort.

 

[/code]

public class InsertionSort

{

public static void main(String args[])

{

 

int array[] = new int[10];

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

array = (int)(java.lang.Math.random()*100);

}

insertionSort(array);

 

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

System.out.println("Val of array[" + i + "] = " +array );

}

 

}

 

public static void insertionSort(int arr[])

{

int j=0;

for (int i=1; i<arr.length;)

{

 

if(arr<arr[j]){

int tmp =arr[j];

arr=arr[j];

arr[j]=tmp;

if(j>0){

j--;

}

else {

j=i;

i++;

}

}

else {

j=i;

i++;

}

 

}

}

}

 

 

[/code]

 

 

Although we dont have two nested loops in this example , nonetheless it worls like two nested loops.

 

the outer loop is only iterated if the present array upto position i is completely sorted. Otherwise j is decremented upto 0 so that the new element a is inserted at its proper position in the partial array.

Share this post


Link to post
Share on other sites

This is my code for an array sorter. It's quite efficient for counting too.

/** * * @author xboxrulz * Source Code is released under CDDL if requested. *  */import java.util.Arrays;public class Main {	/**	 * @param args the command line arguments	 */	public static void main(String[] args) {		int intCount;		String strNames[] = {"Gary", "Adrian", "Corey", "Alex", "Adrien", "Josh", "Zev"};		for (intCount=0; intCount<=6;intCount++)		{			Arrays.sort(strNames);			System.out.println("Hello\t" + strNames[intCount]);		}	}}

Unlike the code provided by the poster above, this one is very human-readable.

Names are people in my class.

xboxrulz

Share this post


Link to post
Share on other sites

He can always implement Comparator interface to do virtually ANYTHING he want. So I wonder why he wants to reinvent the wheels... after all, libraries are tools which makes you NOT to redo what was already done.

I think it is the best solution, provided by Java API - we can simply put desirable business logic of sorting into the method "Comparator::compare()".
I do not any reasons to invent anything else.

For example:

import java.util.Comparator;

public class MyItem implements Comparator {

.......

public int compare(Object o1, Object o2) {
// your business logic of sorting
}

public boolean equals(Object obj) {
// see Sun comments here
}
}

So, we can put objects of MyItem class into appropriated collections (for example, any implementation of SortedSet interface: TreeSet etc.)

Share this post


Link to post
Share on other sites

There are lot's of Array sorting algorithm today, and there is no one best than the other, you will have to choose the one that fits to you depending on the type of data that you need to sort.

In my case I use QuickSort most of the time, is a divide and conquer algorithmic paradigm.

On average, makes O(nlogn) comparisons to sort n items. However, in the worst case, it makes Θ(n^2) comparisons(which is the typical case for other known algorithm like bubble sort).

You can use java.util which brings a class with diverse types of algorithm including this one.

Here you have the code also:

1. pivot = list[sup];                                                                                                                                                                                                               2. i = inf;                                                                                                                                                                                                                   3. j = sup - 1;                                                                                                                                                                                                                   4. cont = 1;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          5. if (inf >= sup)                                                                                                                                                                                                                   6.      return;                                                                                                                                                                                                                                                                                                                                                                                                                                                         7. while (cont)                                                                                                                                                                                                                   8.      while (list[i] < pivot) { ++i; }                                                                                                                                                                                        9.      while (list[j] > pivot) { --j; }                                                                                                                                                                                        10.      if (list[i] > list[j])                                                                                                                                                                                                         11.           temp = list[i];   12.           list[i] = list[j];                                                                                                                                                                                                        13.           list[j] = temp;                                                                                                                                                                                                        14.      else                                                                                                                                                                                                                  15.           cont = 0;                                                                                                                                                                                                         16. temp = list[i];                                                                                                                                                                                                                  17. list[i] = list[sup];                                                                                                                                                                                                         18. list[sup] = temp;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               19. QuickSort (list, inf, i - 1);                                                                                                                                                                                                20. QuickSort (list, i + 1, sup);


-------------
OS:Windows Vista Ultimate Sp1
MD:Asus P5N-E
CPU:2.40GHz/Intel Quad Core Q6600
RAM:Corsair Dual Channel 4GB 800Mhz
VC:XFX GeForce 9800 GTX/512MB

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.