Java data structures and algorithms (iii) -- simple sorting

Source: Internet
Author: User

Java data structures and algorithms (iii) -- simple sorting

Data alone is not enough. Data presentation often needs to be arranged in a certain order. The higher the requirement, the more complicated the sorting. This article only introduces three simple sorting types.

 

1) Bubble Sorting

Simulation: There are arrays.

(1) first, the bubble starts from 1. The value 1 is smaller than 4. If the value 4 is greater than 2, the bubble goes up. If the value 4 is smaller than 5, the bubble goes up. If the value 7 is greater than 3, the result is 1, 2, 4, 5, 3, and 7.

(2) Start from 2. Because the first element has passed, repeat (1) and the result is :,.

(3) starting from 4, the result is 1, 2, 3, 4, 5, and 7.

(4) Although it seems that the order has been arranged, it is still necessary to continue to run. The next step is to start from the 4th bits until the fifth element ends.

 

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:

9 times for the first comparison, 8 times for the second comparison, and 1 time for the last comparison. The total number of comparisons is 9 + 8 +... + !.

 

If N data records exist, 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 is the same as the number of comparisons.

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

 

2) Select sorting

The selection of sorting improves the Bubble sorting and the number of exchanges. It is clear that the number of exchanges O (N ^ 2) is reduced to O (N ). Why?

 

Simulation: There are arrays.

(1) starting from the first element, assume that 1 is the minimum value of the array, min = 1 (min stores the location of the smallest element), start with 1 and compare it with the following elements, if there is another value less than 1 x, assign the position of the x element to min. After comparison, we find that 1 is the smallest. At this time, the minimum value has been placed on the leftmost. Enter (2)

(2) starting from the second value 4, suppose that min = 2, compared with 2, 2 is smaller, min = 3, 2 is compared with 5, or 2 is small, compared with 7, 2 is small, 2 is smaller than 3, and the last min is 3. Replace the positions 2 and 4. The array is.

(3) starting from the third value 4 (switched in the previous step), this time min = 3, and changed to 4. The array is 1, 2, 3, 4, 5, and 7.

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

 

Code:

First knock:

 

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));    }}
Hundreds of errors and omissions.

 

The second time is correct:

 

Public class SelectSort {public static void main (String [] args) {int a [] = {1, 2, 3, 4, 5, 6, 3, 3}; for (int I = 0; I <. length-1; I ++) {int min = I; for (int j = I + 1; j <. length; j ++) {if (a [j] exchange value where and compare where I wrote an error. We have set min to I during the comparison, then, compare min with j. If j is smaller, min = j. Then, when switching values, it does not matter to j. Since the position of the minimum value is locked, you only need to switch with I.

 

An algorithm can be optimized, that is, when the two are equal, there is no need to swap positions. Reduces the value assignment.

 

Complexity:

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

However, the number of exchanges is less than N, so the sort is faster than the bubble. Of course, when the number of elements reaches a certain order of magnitude, the speed is shown.

 

3) Insert sorting

The fastest among the three simple sorting methods, the time complexity is still O (N)

 

After writing the code, explain 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));    }}

Simulation: There are arrays, 1, 3, 2, 4, 2, 5, 7, 3. This is complicated, but not complicated.

 

(1) first, mark points to the insert position. Starting from the second position of the array, the temp value is equal to the element value at the mark position. It is compared to the left, 3 is greater than 1, while loop, a [mark] = temp, that is, 3 does not change, and 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 by 3, compare

The value is reduced by one, that is, 1 and temp are compared, 1 is small, and the while loop is exceeded. a [mark] = temp, that is, the value of 3 is changed to 2.

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

(4) mark + 1: continue the loop. Each time it is marked with a mark, it is compared to the left to keep moving. Until the end.

 

Complexity:

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

The number of copies and comparisons is roughly the same. Although the complexity is O (N ^ 2 ).

However, if the array is 1, 2, 3, 4, 5, 6, 7, 7, that is, the first order is basically ordered. Only when mark is 9, it only exchanges with 8. In this case, the time complexity is only O (N ).

Therefore, insert is twice faster than bubble, and faster than sort.

 

4) Out-of-question-count sorting.

 

I have referenced another blog link above. The three simple sorting complexities all reach O (N ^ 2), even if some advanced sorting is followed by O (NlogN ). Some time ago, I found that there was an order of O (N) Complexity: There are n integers smaller than 100000, and I wrote an algorithm to sort these numbers from small to large, time complexity O (n) and space complexity O (1) are required ).

It turns out to be sorted by count. I found that it was originally in the introduction to algorithms, and I decided to flip the book.

 

Public class SelectSort {public static void main (String [] args) {int a [] = {1, 2, 3, 4, 4, 3, 3 }; int c [] = new int [5]; // c is an array used to store the number of occurrences of each number. for (int I = 0; I <c. length; I ++) {for (int j = 0; j <. 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 [. length]; for (int I = 0; I <. length; I ++) {B [c [a [I]-1] = a [I]; c [a [I] --;} System. out. println (Arrays. toString (B ));}}
The algorithm is too cleverly designed.

 

Array c stores the number of numbers in array a, that is, c [0] indicates the number of numbers 0 in array, therefore, the length of array c must be the maximum element + 1 in array.

 

Then:

 

for (int i = 1; i < c.length; i++) {     c[i] = c[i] +c[i-1];}
In fact, it is the accumulation of the number of times. For example, c [1] = c [1] + c [0], then c [1] stores the number of numbers 0 and 1 in array, similarly, c [2] stores a number smaller than or equal to 2.

 

 

 

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

 

I = 0, a [0] = 1, c [1] is where 1 and 0 appear, 1 and 0 appear twice, since there is no 0, then 1 occupies the first and second places (read this sentence carefully, and the entire algorithm will understand it ). Then we place one of them in the second position B [1] of 1, and c [1]-1 at the same time, because we have already placed one.

 

Next, I = 1, a [1] = 2, c [2] is the number of numbers that appear less than or equal to 2, c [2] = 4, so we need to put it in the fourth place, that is, the position of B [3], and c [2]-1 = 3 at the same time, because a 4 has already arranged the order, so the next time I read 4, he will be in the third place.

 

The next step is to keep the loop. At first, I could not understand the intention of the algorithm designer.

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

 

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.