Sorting algorithm (one) 3 simple sort (selection, bubbling, inserting)

Source: Internet
Author: User

Sorting is a very common and core operation of data processing, although the actual project development of a very small chance will need to be implemented manually, after all, each language in the class library has n more about the implementation of the sorting algorithm. But knowing these ingenious ideas is still a boon to us. In this paper, we simply review the basic three types of algorithms: SELECT, Bubble, insert.

A function to swap array elements is defined first, and is called when sorting

   /**      * Swap array elements      @param  arr     @param  a     @param b      */     Public Static void swap (int []arr,int A,int  b) {        = arr[a]+arr[b];        = arr[a]-arr[b];         = arr[a]-arr[b];    }
Simple selection sorting

Simple selection sorting is the simplest and most intuitive algorithm, the basic idea for each trip from the data element to be sorted by selecting the smallest (or largest) element as the first element , until all the elements are finished, the simple selection of sorting is an unstable sort .

In the implementation of the algorithm, each time the minimum element is determined by the constant comparison of the exchange to make the first position is the current minimum, the exchange is a relatively time-consuming operation. In fact, it is easy to see that these exchanges are meaningless until the current smallest element has been fully determined. We can do this by setting a variable min, and each comparison stores only the array subscripts for smaller elements, and when the cycle ends, that variable stores the subscript of the current smallest element, and then performs the swap operation. The code implementation is simple and looks together.

  Code implementation

    /*** Simple Select sort * *@paramarr*/     Public Static voidSelectsort (int[] arr) {         for(inti = 0; i < arr.length-1; i++) {            intmin = i;//for each cycle comparison, Min is used to store the array subscript of the smaller element, so that the current batch is compared to the bottom of the smallest element in the trip, avoiding the need to exchange the smaller elements each time they are encountered.              for(intj = i + 1; J < Arr.length; J + +) {                if(Arr[j] <Arr[min]) {min=J; }            }            //Exchange if min is changed            if(min! =i) {swap (arr,min,i); }        }    }

Simple selection Sort by the above optimization, regardless of the array original arrangement, the number of comparisons is constant, for the exchange operation, in the best case, when the array is fully ordered, without any exchange movement, in the worst case, that is, the array in reverse order, the number of exchanges is n-1 times. Integration down, time complexity O (n2)

Bubble sort

The basic idea of bubble sorting is to make 22 comparisons of adjacent elements, in reverse order, so that each trip will "float" the smallest or largest element to the top, culminating in an entirely orderly

  

  Code implementation

    In the bubbling sort process, if a trip is completed and no exchange operation is done, such as array [5,4,1,2,3], two bubbles are performed, i.e. two outer loops, respectively, 5 and 4 are adjusted to the final position [1,2,3,4,5]. At this point, after the third loop, a swap is not done, which means that the rest of the sequence is already ordered, the sorting operation can be done, to see the code

 /*** Bubble Sort * *@paramarr*/     Public Static voidBubblesort (int[] arr) {         for(inti = 0; i < arr.length-1; i++) {            BooleanFlag =true;//setting a token, if true, indicates that the loop has not been exchanged, that is, the order is ordered and the ordering is complete.              for(intj = 0; J < arr.length-1-I; J + +) {                if(Arr[j] > arr[j + 1]) {Swap (Arr,j,j+1); Flag=false; }            }            if(flag) { Break; }        }    }

According to the above bubbling implementation, the Wakahara array itself is ordered (this is the best case), only need to n-1 the comparison can be done, if the reverse, the number of comparisons is n-1+n-2+...+1=n (n-1)/2, the number of exchanges and the number of comparisons equivalent. Therefore, its time complexity is still O (n2). Overall, the bubble sort performance is still slightly worse than the sort of choice above.

Insert Sort

The basic idea of inserting a sort is to insert a record to be sorted at each step, inserting it into an ordered sequence that is already ordered, until all elements have been inserted.

Code implementation

    /*** Insert Sort * *@paramarr*/     Public Static voidInsertionsort (int[] arr) {         for(inti = 1; i < arr.length; i++) {            intj =i;  while(J > 0 && arr[j] < arr[j-1]) {Swap (Arr,j,j-1); J--; }        }    }

Simple insert sort in the best case, you need to compare n-1 times, without exchanging elements, with a time complexity of O (n), and in the worst case, the time complexity remains O (N2). However, if the array elements are randomly arranged, the insertion sort is better than the above two sorts.

Summarize

This article lists the ranking algorithm in the most basic three kinds of algorithms (simple selection, bubbling, insertion), the time complexity of the three sorting algorithms are O (N2), follow-up will be updated in succession to some other higher order algorithm, time complexity will gradually break through O (N2), thank you for your support.

Sorting algorithm (one) 3 simple sort (selection, bubbling, inserting)

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.