Java data structure and algorithms (iii)--simple sort __ Storage

Source: Internet
Author: User

This series of articles has a lot of mistakes, too sloppy, not carefully tested, the beginning to write better, to the misguided people apologize, their attitude is problematic. The wrong place will be repaired. Too many things have happened to SpongeBob.

There is no need to erase, wrong is wrong. Thank you for your correction.



Data alone is not enough, for the presentation of data, often to be arranged in a certain order, the higher the requirements of the sorting more complex, this article only describes three kinds of simple sorting.


1) Bubble sort

Before the wrong, has been corrected, to bring inconvenience to everyone, sorry.



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

Bubbling is equivalent to a bubble upward, from physics know light is on the top.

(1) Starting from 1 bubble, 1:4 small, with 1 exchange position, upward, 1 less than 2, run, with 2 Exchange position, 1:5 small, run, 1 with 5 Exchange position, 1:3, take, with 5 exchange position, so always, the result: 4,2,5,7,3,1.

(2) The next starting from 4, because the last bubble is the lightest, so do not take, so need to deal with is 4,2,5,7,3.

4:2 Heavy, not run, 2:5 light, take up. Repeat the process. Result: 4,5,7,3,2,1

(3) The bottom two is the lightest, no need to take, so 4 goes up to the front, and the result is 5,7,4,3,2,1.

(4) Repeat the process, the light always take, the result is 7,5,4,3,2,1


Code:

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


About the threshold: I starting from 0, i<a.length-1, because there are 10 numbers, to the last largest number is already at the bottom, so the last time can be ignored without comparison.

Degree of complexity:

10 number, the first 9 times comparison, the second 8 times, the last 1 times, the total number of comparisons 9+8+......+1 (I use the factorial expression here to write 9.) , really embarrassed, in fact, this is a difference group, thank users to remind.

If N data, that comparison is total m=n* (N-1)/2, the number of exchanges is probably half of the comparison, N (N-1)/4, the worst time and the comparison times.

Remove constant, Time complexity O (n^2).


2) Select Sort

The select sort improves the bubbling sort, the number of exchanges, and it is clear that the number of exchanges O (n^2) is reduced to O (N). Why.


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

(1) Starting with the first element, assuming a minimum of 1 arrays, min=1 (min holds the position of the smallest element), with 1 starting and trailing elements, and if there is a value x that is smaller than 1, assign the position of the X element to Min, and then find the 1 min after comparison. At this time, the smallest value has been placed on the leftmost, into (2)

(2) Starting from the second value of 4, assuming that min=2, compared with 2, 2 smaller, min=3,2 again with 5, or 2 small, with 7, 2 small, and 3, 2 small, the last min=3, at the same time will be 2 and 4 replacement position. The array is: 1,2,4,5,7,3.

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

(4) Starting from the fourth value 4, this time min is 4, and so on. Finally: 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));
    }
Mistakes.

Second time:

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]) {
                    min = j;
                }
            }
            If the min position has not changed, then the minimum value is not required to Exchange
            if (min!= i) {
            	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, itself compared to the time we have to set the Min to start, then is the Min and J than, if J is smaller, then min=j. Then, when the value is exchanged, it is not related to J, since the position of the minimum value is locked, as long as it is exchanged with I.

The algorithm has a place to optimize, that is, when the two are equal, they do not have to swap positions. reduced the assignment at once.


Degree of complexity:

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

But the number of exchanges is less than N, think bubble is the end of each time, it is necessary to exchange, and the choice is only the last time. And so the choice of ordering is faster than bubbling, of course, when the element reaches a certain order of magnitude, the speed is reflected.


3) Insert Sort

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


This is done by writing code to 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 (compare>0&&a[compare-1]>temp) {
                A[compare] = a[compare-1];
                compare--;
            }
            A[compare] =temp
        }
        System.out.println (Arrays.tostring (a));
    }




Simulation: There are arrays, 1,3,2,1,4,2,5,7,3. This is a bit more complicated, but it's not complicated.

(1) First mark points to the insertion position, starting at the second position of the array, the temp value equals Mark's element value, to the left, 3 is greater than the 1,while loop, A[mark]=temp, or 3 is unchanged, the next for loop.

(2) mark=2, pointing to 2,temp=2, left, 3 greater than temp, so 2 replaces 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 of 2.

(3) The array is now, 1,2,3,1,4,2,5,7,3,mark=3, pointing to the 1,temp=1, to the left, 3 greater than 1,a[compare], that is, a[3]=a[2]=3, then to the left, compare minus one, compare=2,2 greater than 1, so a[ Compare],a[2]=a[1]=2, this is 1,2,2,3,4,2,5,7,3. On the left, compare minus one, a[0]=1, not moving, finally a[1]=temp=1, into 1,1,2,3,4,2,5,7,3.

(4) Mark+1, continue to cycle, each time is to mark as a sign, the left to compare size, keep moving. Until the end.


Degree of complexity:

The number of comparisons seems to be the same difference group directly calculates--n* (N-1)/2, but in fact after each insertion point, the data in front of the insertion point is ordered, so the real comparison is only about half--n* (N-1)/4,

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

But if the array is 1,2,3,4,5,6,7,8,7, that is, the front is basically orderly, it only compares when Mark equals 9, and it only exchanges with 8. So the time complexity is only O (N).

So inserting is one times faster than bubbling, faster than choosing a sort.


4) Outside the question--counting sort.

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 an array for
		(int j = 0; J < A.length; J +) {c[a[j]]++;}
		 
		*
		 * Old Code
		 * The loop here is redundant, the size of the value determines the position, so the direct use of c[a[j]]++ can be counted 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, 3] Originally written incorrectly, "0,2,2,3,2" 4 has 3 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, ten]  , the relative is also written incorrectly.
        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));
    }


This refers to another blog link, the simple three sorts of sorting complexity to O (n^2), even if the next advanced some of the order is to O (Nlogn). Some time ago to see the topic found that there is an O (n) Complexity of the order: the existing N less than 100000 of integers, write an algorithm to these numbers from small to large order, requiring time complexity O (n), Space complexity O (1).

The original is to use the sort of counting. found that the original algorithm in the introduction of some, decisively turn the book.


The algorithm is designed to be ingenious.

The C array stores the number of digits in a array, that is, c[0] represents the number of 0 occurrences in a, and because of this, the length of the C array is the largest element +1 in the array A.


And then:

for (int i = 1; i < c.length i++) {
     c[i] = c[i] +c[i-1];
In fact, is the cumulative number of times, such as C[1]=c[1]+c[0], then c[1] is the number of a array of 0 and 1, 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 where the algorithm is most beautiful.

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 occupied the first and second position (please read this sentence carefully, this sentence read, the whole algorithm is understood). Then we put one of the 1 in the position of the second b[1 of 1, and c[1]-1, because we've already lined up a 1.


(Actually, after being wrongly accused, I looked at it again.) In fact, the idea is to find this number, see the number row in the first few, because the initial coordinates of the array is 0, then move forward one bit. Then after this number, the number of storage is reduced by 1.


Next, I=1,a[1]=2,c[2] is less than or equal to 2 of the number of numbers, c[2]=4, then put it in fourth, that is b[3] position, while c[2]-1=3, because a 4 has been ordered, then next time to read 4, he is the third position.


The next step is a non-stop cycle, just beginning to see the idea of algorithmic designers.

In fact, the relationship between order and size appears to be so wonderful.


The code in the comments is actually more subtle:

int a[] = {1,2,3,4,4,4,3,1,2,3}; 
int c[] = new INT[5];
for (int i=0;i<c.length;i++) {for
(int j=0;j<a.length;j++) {
if (a[j) = i) {
c[i]++
}
}} int index = 0;
for (int j=0;j<c.length;j++) {for
(int i=index;i<index + c[j];i++) {
a[i] = j;
}
Index +=c[j];
}
System.out.println (Arrays.tostring (a));

Directly according to the number of sorting can be more in line with the algorithm, more simple than the above.

for (int i=0;i<a.length;i++) {
c[a[i]]++
}

If you want to learn the algorithm in depth-"Introduction to Algorithms" is a very good book.

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.