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

Thread: Sorting Arrays

  1. #1
    Code Slinger chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5's Avatar
    Join Date
    Mar 2008
    Posts
    7,023
    Blog Entries
    1

    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. #2
    Administrator Jordan is a name known to all Jordan is a name known to all Jordan is a name known to all Jordan is a name known to all Jordan is a name known to all Jordan is a name known to all Jordan's Avatar
    Join Date
    Nov 2005
    Location
    Hendersonville, NC
    Posts
    24,556
    Blog Entries
    97

    Re: Sorting Arrays

    Great tutorial! +rep

  3. #3
    Code Warrior Turk4n has much to be proud of Turk4n has much to be proud of Turk4n has much to be proud of Turk4n has much to be proud of Turk4n has much to be proud of Turk4n has much to be proud of Turk4n has much to be proud of Turk4n has much to be proud of Turk4n's Avatar
    Join Date
    May 2008
    Location
    4chan.org/g/
    Age
    20
    Posts
    3,836
    Blog Entries
    4

    Re: Sorting Arrays

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

    Hatsune Miku ~❤❤❤
    初音ミク。~❤❤❤

  4. #4
    Super Moderator WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther's Avatar
    Join Date
    Jul 2006
    Age
    36
    Posts
    11,668
    Blog Entries
    57

    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

  5. #5
    Code Slinger chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5's Avatar
    Join Date
    Mar 2008
    Posts
    7,023
    Blog Entries
    1

    Re: Sorting Arrays

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

  6. #6
    Super Moderator WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther's Avatar
    Join Date
    Jul 2006
    Age
    36
    Posts
    11,668
    Blog Entries
    57

    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

  7. #7
    Code Slinger chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5 has a reputation beyond repute chili5's Avatar
    Join Date
    Mar 2008
    Posts
    7,023
    Blog Entries
    1

    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.

  8. #8
    Super Moderator WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther has much to be proud of WingedPanther's Avatar
    Join Date
    Jul 2006
    Age
    36
    Posts
    11,668
    Blog Entries
    57

    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

  9. #9
    Guru MathX has a spectacular aura about MathX has a spectacular aura about MathX's Avatar
    Join Date
    Oct 2008
    Location
    Kosovo
    Age
    19
    Posts
    4,006

    Re: Sorting Arrays

    Very Very Nice

  10. #10
    Newbie Benbo is an unknown quantity at this point
    Join Date
    Sep 2009
    Location
    Norway
    Age
    15
    Posts
    18

    Re: Sorting Arrays

    Very nice, +rep

+ Reply to Thread
Page 1 of 2
1 2 LastLast

Thread Information

Users Browsing this Thread

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

     

Similar Threads

  1. Simple Arrays Sorting Help?
    By Puff in forum C and C++
    Replies: 17
    Last Post: 08-15-2009, 02:23 PM
  2. PHP Arrays
    By chili5 in forum PHP Tutorials
    Replies: 7
    Last Post: 05-22-2009, 04:16 PM
  3. Sorting Array's
    By ahmed in forum C and C++
    Replies: 9
    Last Post: 12-03-2008, 11:00 AM
  4. Help regarding the sorting of arrays with flags!
    By Yuriy M in forum C and C++
    Replies: 3
    Last Post: 10-12-2007, 10:30 PM
  5. Sorting Arrays
    By falco85 in forum PHP Forum
    Replies: 5
    Last Post: 08-23-2006, 09:31 PM

Bookmarks

Bookmarks

     
        Algorithms and Data Structures

        Java tutorials

        Algorithms Forum

Posting Permissions

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