Go Back   CodeCall Programming Forum > Software Development > Tutorials > Java Tutorials
Register Blogs Search Today's Posts Mark Forums Read

Java Tutorials Tutorials and Code for Java

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 08-26-2009, 08:11 PM
chili5's Avatar
Code Slinger
 
Join Date: Mar 2008
Posts: 7,018
chili5 has a reputation beyond reputechili5 has a reputation beyond reputechili5 has a reputation beyond reputechili5 has a reputation beyond reputechili5 has a reputation beyond reputechili5 has a reputation beyond reputechili5 has a reputation beyond reputechili5 has a reputation beyond reputechili5 has a reputation beyond reputechili5 has a reputation beyond reputechili5 has a reputation beyond repute
Sorting Arrays

Sorting Arrays

In some cases, you might want to sort an array. It might be an array of objects or a primitive array. Either way you can use the java.util.Arrays class to sort the array.

This method uses a modified quick sort algorithm that runs in 0(nlogn) time. This is considerably faster than bubble sort and other sort algorithms.

The java.util.Arrays class defines a static sort method for each primitive data type and a method that takes an array of type Object. This allows you to sort an array of any data type you want.

This method is a void method because arrays are based by reference. Thus if the array is modified in the function, then the array is modified outside of the function as well. If you want to retain the array, you must use the Arrays.copyOf method to make a copy of it before you pass it to the sort method.

Examples of sorting:

Code:
int[] v = {3,2,7,4,-1,5};
long[] l = {3,2,5,4,3,2,5,9};
String[] names = {"James","bob","test"};

Arrays.sort(v);
Arrays.sort(l);
Arrays.sort(names);

for (int i=0;i<v.length;i++) {
       System.out.print(v[i] + " ");
}
System.out.println();

for (int i=0;i<l.length;i++) {
            System.out.print(l[i] + " ");
}
System.out.println();

for (int i=0;i<names.length;i++) {
      System.out.print(names[i] + " ");
}
System.out.println();
The for loops are to show you the output to notice, that the arrays are now in ascending order. The String sort takes a bit more explanation though. The strings are sorted by there unicode values. Which is a value for the string by adding all the ASCII values for each character together.

I'm a bit disappointed in this class that it defines a sort method for each data type. It would be much more maintainable if it used a generic method. However, generic methods don't work with primitives to they are left with no choice.

Example of sorting and retaining the original array:

Code:
int[] v = {3,2,5,7,9,2,4};
int[] copy = v.clone();

// Now we can pass the array to the method
Arrays.sort(v);
This allows you to retain the original array, and get a copy that is sorted.

If you don't know how I copied the array, see my tutorial here: Copying Arrays.

Comparator

To sort objects of a programmer defined data type the data type you supporting must implement the Comparable interface.

Let us first define a class that we can use:

Code:
class nums {
    int i;

    nums(int i) {
        this.i = i;
    }

public int compareTo(Object o) {
        nums temp = (nums)o;

        if (temp.i < i) {
            return 1;
        } else if (temp.i == i) {
            return 0;
        }
        return -1;

    }
}
The compareTo method takes an object to compare with and returns 1 if the passed object's i value is less than the other object's i value. It will return 0 if they are equal and -1 otherwise. This is all the Arrays.sort method needs.

Now we are going to create an array of nums with random numbers.

Code:
nums[] aroNums = new nums[10];

 for (int i=0;i<10;i++) {
      aroNums[i] = new nums((int)(Math.random()*10)+5);
}
First we allocate an array of 10 nums and then initialize 10 objects. Now if you call Arrays.sort by passing aroNums the array will be sorted based on the i values.

Code:
for (int i=0;i<aroNums.length;i++) {
        System.out.print(aroNums[i].i + " ");
}
System.out.println();
Output:

Quote:
5 5 5 6 10 11 12 14 14 14
This comes in handy with different programming problems, and in the implementation of different data structures.


Try this problem out:
London Knights. This is an exercise in sorting objects.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #2 (permalink)  
Old 08-26-2009, 08:15 PM
Jordan's Avatar
Administrator
 
Join Date: Nov 2005
Location: Hendersonville, NC
Posts: 24,556
Jordan is a name known to allJordan is a name known to allJordan is a name known to allJordan is a name known to allJordan is a name known to allJordan is a name known to all
Send a message via ICQ to Jordan Send a message via AIM to Jordan Send a message via MSN to Jordan Send a message via Yahoo to Jordan
Re: Sorting Arrays

Great tutorial! +rep
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 08-27-2009, 01:10 AM
Turk4n's Avatar
Code Warrior
 
Join Date: May 2008
Location: 4chan.org/g/
Age: 20
Posts: 3,822
Turk4n has much to be proud ofTurk4n has much to be proud ofTurk4n has much to be proud ofTurk4n has much to be proud ofTurk4n has much to be proud ofTurk4n has much to be proud ofTurk4n has much to be proud ofTurk4n has much to be proud of
Send a message via MSN to Turk4n Send a message via Skype™ to Turk4n
Re: Sorting Arrays

Wow, fun thing to try out thanks !
Also gr8 tutorial
rep+
__________________

Hatsune Miku ~❤❤❤
初音ミク。~❤❤❤
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #4 (permalink)  
Old 08-27-2009, 11:53 AM
WingedPanther's Avatar
Super Moderator
 
Join Date: Jul 2006
Age: 36
Posts: 11,435
WingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud of
Re: Sorting Arrays

You said it's O(n log n). Is that average, worst case, other? +rep
__________________
CodeCall Blog | CodeCall Wiki | Shareware
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #5 (permalink)  
Old 08-27-2009, 12:00 PM
chili5's Avatar
Code Slinger
 
Join Date: Mar 2008
Posts: 7,018
chili5 has a reputation beyond reputechili5 has a reputation beyond reputechili5 has a reputation beyond reputechili5 has a reputation beyond reputechili5 has a reputation beyond reputechili5 has a reputation beyond reputechili5 has a reputation beyond reputechili5 has a reputation beyond reputechili5 has a reputation beyond reputechili5 has a reputation beyond reputechili5 has a reputation beyond repute
Re: Sorting Arrays

Average. In the worst case it is 0(n^2).
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #6 (permalink)  
Old 08-27-2009, 12:45 PM
WingedPanther's Avatar
Super Moderator
 
Join Date: Jul 2006
Age: 36
Posts: 11,435
WingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud of
Re: Sorting Arrays

It's probably QuickSort, then
__________________
CodeCall Blog | CodeCall Wiki | Shareware
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #7 (permalink)  
Old 08-27-2009, 01:05 PM
chili5's Avatar
Code Slinger
 
Join Date: Mar 2008
Posts: 7,018
chili5 has a reputation beyond reputechili5 has a reputation beyond reputechili5 has a reputation beyond reputechili5 has a reputation beyond reputechili5 has a reputation beyond reputechili5 has a reputation beyond reputechili5 has a reputation beyond reputechili5 has a reputation beyond reputechili5 has a reputation beyond reputechili5 has a reputation beyond reputechili5 has a reputation beyond repute
Re: Sorting Arrays

I know it is QuickSort. One thing I don't get is why it is 0(nlogn) and sometimes 0(n^2). I read about quick sort in a book and thought huh?

I got merge sort but quick sort makes no sense to me.

The naming conventions in the Arrays class suck. They have methods: sort, sort1, sort2, etc...

The sort method is:

Code:
private static void sort1(int x[], int off, int len) {
	// Insertion sort on smallest arrays
	if (len < 7) {
	    for (int i=off; i<len+off; i++)
		for (int j=i; j>off && x[j-1]>x[j]; j--)
		    swap(x, j, j-1);
	    return;
	}

	// Choose a partition element, v
	int m = off + (len >> 1);       // Small arrays, middle element
	if (len > 7) {
	    int l = off;
	    int n = off + len - 1;
	    if (len > 40) {        // Big arrays, pseudomedian of 9
		int s = len/8;
		l = med3(x, l,     l+s, l+2*s);
		m = med3(x, m-s,   m,   m+s);
		n = med3(x, n-2*s, n-s, n);
	    }
	    m = med3(x, l, m, n); // Mid-size, med of 3
	}
	int v = x[m];

	// Establish Invariant: v* (<v)* (>v)* v*
	int a = off, b = a, c = off + len - 1, d = c;
	while(true) {
	    while (b <= c && x[b] <= v) {
		if (x[b] == v)
		    swap(x, a++, b);
		b++;
	    }
	    while (c >= b && x[c] >= v) {
		if (x[c] == v)
		    swap(x, c, d--);
		c--;
	    }
	    if (b > c)
		break;
	    swap(x, b++, c--);
	}

	// Swap partition elements back to middle
	int s, n = off + len;
	s = Math.min(a-off, b-a  );  vecswap(x, off, b-s, s);
	s = Math.min(d-c,   n-d-1);  vecswap(x, b,   n-s, s);

	// Recursively sort non-partition-elements
	if ((s = b-a) > 1)
	    sort1(x, off, s);
	if ((s = d-c) > 1)
	    sort1(x, n-s, s);
    }
I just don't get how it works at all. This code is nothing like the code in my book.

Is it 0(n^2) in the worst case because of the insertion sort? I don't know.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #8 (permalink)  
Old 08-28-2009, 11:26 AM
WingedPanther's Avatar
Super Moderator
 
Join Date: Jul 2006
Age: 36
Posts: 11,435
WingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud ofWingedPanther has much to be proud of
Re: Sorting Arrays

Many sort algorithms have a variable performance depending on the order the data is in. Bubble sorts are O(n) on sorted data, for example (assuming there's a bailout when no swaps are made).

Quicksort get's O(n^2) when the data is REVERSED (if I recall correctly). Heap-sort avoids this problem. C++ uses a mixture of methods depending on the data being sorted.
__________________
CodeCall Blog | CodeCall Wiki | Shareware
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #9 (permalink)  
Old 08-29-2009, 10:13 AM
MathX's Avatar
Guru
 
Join Date: Oct 2008
Location: Kosovo
Age: 19
Posts: 3,994
MathX has a spectacular aura aboutMathX has a spectacular aura about
Send a message via MSN to MathX
Re: Sorting Arrays

Very Very Nice
__________________
My Blog
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #10 (permalink)  
Old 09-21-2009, 11:32 AM
Newbie
 
Join Date: Sep 2009
Location: Norway
Age: 15
Posts: 17
Benbo is an unknown quantity at this point
Send a message via MSN to Benbo
Re: Sorting Arrays

Very nice, +rep
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes


Similar Threads
Thread Thread Starter Forum Replies Last Post
Simple Arrays Sorting Help? Puff C and C++ 17 08-15-2009 03:23 PM
PHP Arrays chili5 PHP Tutorials 7 05-22-2009 05:16 PM
Sorting Array's ahmed C and C++ 9 12-03-2008 12:00 PM
Help regarding the sorting of arrays with flags! Yuriy M C and C++ 3 10-12-2007 11:30 PM
Sorting Arrays falco85 PHP Forum 5 08-23-2006 10:31 PM


All times are GMT -5. The time now is 11:40 PM.


vBulletin v3.8.0 ©2010, Jelsoft Enterprises Ltd.


no new posts

LinkBacks Enabled by vBSEO 3.1.0