Java Data structures and algorithms (iii)--Simple sorting

Source: Internet
Author: User

Data alone is not enough, for the presentation of data, often in a certain order to arrange, the higher the ordering of the more complex, this article only introduces three sizes of simple sorting.


1) Bubble sort

Analog: There are arrays, 1,4,2,5,7,3.

(1) First starting from 1 bubbles, 1:4 Small, do not take, 4 more than 2, take up, with 2 exchange position, 4:5 small, do not take, 7:3 large, take, result: 1,2,4,5,3,7

(2) Next starting from 2, because the first element has run over, repeat (1), Result: 1,2,4,3,5,7

(3) Starting from the third digit 4, the result 1,2,3,4,5,7

(4) Although it seems to have been sequenced, but continue to take, the next step is to start from the 4th position, until the fifth element to run out.


Code:

public class bubblesort{public      static void Main (string[] args) {        int a[] = {1,2,3,4,5,6,3,1,2,3};        for (int i = 0, i < a.length-1; i++) {for            (int j = i; J < A.length; J + +) {                if (A[i]>a[j]) {                    int temp = A[J];                    A[J] = A[i];                    a[i]=temp;}}}}    


Complexity of:

First 9 comparisons, second 8 times, last 1 times, compare Total 9+8+......+1,9!.

If n data, then the comparison is n! =n* (N-1)/2, the number of exchanges is about half of the comparison,N (N-1)/4, the worst time and the same number of comparisons.

Remove the constant, time complexity O (n^2).


2) Select sort

The choice of sorting improved the bubbling sort, the number of exchanges, and the number of times O (n^2) of the interchange was reduced to O (N). Why?


Analog: There are arrays, 1,4,2,5,7,3.

(1) Starting from the first element, assuming that 1 is the smallest value of the array, min=1 (min holds the position of the smallest element), 1 starts with the following elements, if there is a smaller than 1 value x, the X element is located in the position assigned to min, compared to find 1 min. At this time, the smallest value has been left on the leftmost, enter (2)

(2) Starting from the second value of 4, assuming that min=2, compared with 2, 2 is smaller, min=3,2 again with 5, or 2 small, and 7, 2 small, and 3, 2 small, and finally min=3, while replacing 2 and 4 position. The array is: 1,2,4,5,7,3.

(3) Starting from the third value of 4 (previous exchange), this time min=3, and 4 transposition. The array is: 1,2,3,4,5,7.

(4) Starting from the fourth value of 4, this time min is 4, and so on. Last: 1,2,3,4,5,7.


Code:

For the first time knocking:

public class selectsort{public      static void Main (string[] args) {        int a[] = {1,2,3,4,5,6,3,1,2,3};        for (int i = 0; i < a.length-1; i++) {            int min = i;            Int J =0;            for (j= i+1; j < A.length-1; J + +) {                if (A[i]>a[j]&&a[i]!=a[j]) {                    min = j;                }            }            int temp = A[i];            A[i] = a[min];            A[J] = temp;        }        System.out.println (Arrays.tostring (a));}    }
The mistakes are flawed.

Second time correct:

public class selectsort{public      static void Main (string[] args) {        int a[] = {1,2,3,4,5,6,3,1,2,3};        for (int i = 0; i < a.length-1; i++) {            int min = i;            for (int j= i+1; j < A.length; J + +) {                if (A[j]<a[min]&&a[j]!=a[min]) {                    min = j;                }            }            int temp = A[i];            A[i] = a[min];            A[min] = temp;        }        System.out.println (Arrays.tostring (a));}    }
Exchange values there and compare there I wrote wrong, by itself compared to the time we have set min to start, then the Min and J ratio, if J is smaller, then min=j. Then, when exchanging values, and J is also not related, since the location of the minimum value is locked, as long as and I exchange.

The algorithm has a place to optimize, that is, when the two are equal, they do not have to swap positions. Reduced the value of a single assignment.


Complexity of:

In fact, the number of comparisons is the same as bubbling-factorial-n!=n* (N-1)/2. (n elements)

But the number of exchanges is less than N, so choose to sort faster than bubbling, of course, when the elements reached a certain number of levels, the speed is reflected.


3) Insert Sort

In the simple sort of these three kinds of the fastest, the time complexity is still O (N)


This writes out the code and then explains the simulation process:

Code:


public class Insertsort {public    static void Main (string[] args) {        int[] a = {1,3,2,1,4,2,5,7,3};        int mark,compare;        for (Mark = 1;mark < a.length;mark++) {            int temp = A[mark];            Compare = Mark;            while (a[compare-1]>temp&&compare-1>0) {                A[compare] = a[compare-1];                compare--;            }            A[compare] =temp;        }        System.out.println (Arrays.tostring (a));}    }

Analog: There are arrays, 1,3,2,1,4,2,5,7,3. this is complicated, but it's not complicated.

(1) First mark points to the inserted position, starting at the second position of the array, the temp value equals the element value of the mark position, the left comparison, 3 is greater than the 1,while loop, the A[mark]=temp, or 3 does not change, the next for loop.

(2) mark=2, pointing to 2,temp=2, to the left, 3 is greater than temp, so the value of 2 is replaced 3,compare

The value minus one, will be 1 and temp comparison, 1 small, jump out while loop, a[mark]=temp, that is, 3 of the value into 2.

(3) array is now, 1,2,3,1,4,2,5,7,3,mark=3, point to 1,temp=1, left, 3 greater than 1,a[compare], that is a[3]=a[2]=3, then left, compare minus one, compare=2,2 greater than 1, so a[ Compare],a[2]=a[1]=2, this time for 1,2,2,3,4,2,5,7,3. In the left, compare minus one, a[0]=1, do not move, finally a[1]=temp=1, become 1,1,2,3,4,2,5,7,3.

(4) Mark+1, continue the cycle, each time is marked as Mark, to the left compared to the size, keep moving. Until the end.


Complexity of:

The number of comparisons seems to be factorial-n!=n* (N-1)/2, but after each insertion point the data in front of the insertion point is ordered, so the real comparison is only about half--n!=n* (N-1)/4,

The number of copies and comparisons is roughly equal. Although the complexity is also O (n^2).

But if the array is 1,2,3,4,5,6,7,8,7, which is basically ordered before, it will only compare when Mark equals 9, and only swap with 8. In that case, the time complexity is only O (N).

So inserting is a bit faster than bubbling, faster than selecting sort.


4) out of the question--counting sort.


There is another blog link above, with a simple three sorting complexity of O (n^2), even if the next advanced sort is O (Nlogn). The previous period of time to see the topic found that there is an O (n) Complexity of the order: the existing N is less than 100000 integers, write an algorithm to order these numbers from small to large, requiring time complexity O (N), Spatial complexity O (1).

The original is to use the count sort. found that the original algorithm in the introduction of some, decisive turn over the book.

public class selectsort{public      static void Main (string[] args) {        int a[] = {1,2,3,4,4,4,3,1,2,3};        int c[] = new int[5];//c is the array used to hold each number occurrence number for        (int i = 0; i < c.length; i++) {for            (int j = 0; j < A.length; J + +) {                if (i = = A[j])                    c[i]++;}        }        System.out.println (Arrays.tostring (c));        [0, 2, 2, 3, 2] for        (int i = 1; i < c.length; i++) {            c[i] = c[i] +c[i-1];        }        System.out.println (Arrays.tostring (c));        [0, 2, 4, 7, 9]        int[] b = new Int[a.length];        for (int i = 0; i < a.length; i++) {            b[c[a[i]]-1] = a[i];            c[a[i]]--;        }        System.out.println (arrays.tostring (b));}    }
the algorithm has been designed too cleverly.

The C array is the number of occurrences of the number in the stored a array, i.e. c[0] represents the number of occurrences of 0 in a, and because of this, the length of the C array is the largest element in the a array of +1.


And then:

for (int i = 1; i < c.length; i++) {     c[i] = c[i] +c[i-1];}
In fact, the cumulative number of times, such as C[1]=c[1]+c[0], then c[1] is a array of a 0 and 1, and so on, and so on, c[2] is less than or equal to 2 of the number.


for (int i = 0; i < a.length; i++) {      b[c[a[i]]-1] = a[i];      c[a[i]]--;}
This is the most beautiful place in the algorithm.

I=0,A[0]=1,C[1] is 1 and 0 occurrences of the place, 1 and 0 appear two times, since there is no 0, then 1 is occupy the first and second position (please read this sentence carefully, this sentence read, the whole algorithm understand). Then we put one of the 1 in the position of the second position of the 1 b[1], while c[1]-1, because we have already lined up a 1.


Next, I=1,a[1]=2,c[2] is less than or equal to 2 of the number of occurrences, c[2]=4, then to rank it in fourth place, that is b[3] position, while c[2]-1=3, because a 4 has been ordered, then the next time you read 4, he is the location of old three.


The next step is to keep the loop, just beginning to understand the intent of the algorithm designer.

In fact, the relationship between the order and the size of the number of occurrences is so wonderful.


If you want to learn more about algorithms-the introduction to algorithms is a very good book.

Java Data structures and algorithms (iii)--Simple sorting

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.