+ Reply to Thread
Page 1 of 2 12 LastLast
Results 1 to 10 of 12

Thread: Sorting Arrays

  1. #1
    Join Date
    Mar 2008
    Posts
    7,145
    Rep Power
    86

    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:

    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.

  2. CODECALL Circuit advertisement
    Join Date
    Always
    Posts
    Many

     
  3. #2
    Jordan Guest

    Re: Sorting Arrays

    Great tutorial! +rep

  4. #3
    Join Date
    May 2008
    Location
    Hell
    Posts
    3,851
    Blog Entries
    4
    Rep Power
    49

    Re: Sorting Arrays

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

  5. #4
    Join Date
    Jul 2006
    Posts
    16,486
    Blog Entries
    75
    Rep Power
    143

    Re: Sorting Arrays

    You said it's O(n log n). Is that average, worst case, other? +rep
    Programming is a branch of mathematics.
    My CodeCall Blog | My Personal Blog

  6. #5
    Join Date
    Mar 2008
    Posts
    7,145
    Rep Power
    86

    Re: Sorting Arrays

    Average. In the worst case it is 0(n^2).

  7. #6
    Join Date
    Jul 2006
    Posts
    16,486
    Blog Entries
    75
    Rep Power
    143

    Re: Sorting Arrays

    It's probably QuickSort, then
    Programming is a branch of mathematics.
    My CodeCall Blog | My Personal Blog

  8. #7
    Join Date
    Mar 2008
    Posts
    7,145
    Rep Power
    86

    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.

  9. #8
    Join Date
    Jul 2006
    Posts
    16,486
    Blog Entries
    75
    Rep Power
    143

    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.
    Programming is a branch of mathematics.
    My CodeCall Blog | My Personal Blog

  10. #9
    Join Date
    Oct 2008
    Location
    Istog, Kosova
    Posts
    4,001
    Blog Entries
    1
    Rep Power
    40

    Re: Sorting Arrays

    Very Very Nice
    Interested in participating in community events?
    Want to harness your programming skill and turn it into absolute prowess?
    Come join our programming events!

  11. #10
    Benbo is offline Newbie
    Join Date
    Sep 2009
    Location
    Norway
    Posts
    20
    Rep Power
    0

    Re: Sorting Arrays

    Very nice, +rep

+ Reply to Thread
Page 1 of 2 12 LastLast

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Sorting Values from Arrays
    By An Alien in forum Java Help
    Replies: 13
    Last Post: 03-06-2011, 06:36 PM
  2. Need help sorting 2 arrays.
    By posto2012 in forum C and C++
    Replies: 3
    Last Post: 10-11-2009, 04:46 PM
  3. Simple Arrays Sorting Help?
    By Puff in forum C and C++
    Replies: 17
    Last Post: 08-15-2009, 12:23 PM
  4. Help regarding the sorting of arrays with flags!
    By Yuriy M in forum C and C++
    Replies: 3
    Last Post: 10-12-2007, 08:30 PM
  5. Sorting Arrays
    By falco85 in forum PHP Development
    Replies: 5
    Last Post: 08-23-2006, 07:31 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts