Graphical sorting algorithm (i) 3 simple sort (selection, bubbling, direct insertion)

Source: Internet
Author: User

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

/**      * Swap array elements      @param  arr     @param  a      @param  b     *    /publicstaticvoid swap (int []arr, int A,int  b) {        = arr[a]+arr[b];         = arr[a]-arr[b];         = arr[a]-arr[b];    }
Simple selection sorting (O (n^2))

Simple selection of sorting is the simplest and most intuitive algorithm.

Basic idea: each trip selects the smallest (or largest) element of the data element to be sorted as the first element , and the simple selection is an unstable sort until all the elements have been exhausted.

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.

/*** 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. Synthesis down, time complexity O (n2)

Bubble sort (O (n^2))

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 completed; In reverse order, The number of comparisons is n-1+n-2+ ... +1=n (n-1)/2, the number of exchanges and the number of comparisons are equivalent. Therefore, its time complexity is still O (n2). Overall, the bubble sort performance is still slightly worse than the sort of choice above.

Direct Insert Sort (O (n^2))

Direct insertion sort The basic idea is that each step is to insert a record to be sorted into an ordered sequence that is already in sequence until all elements have been inserted.

Code implementation

(1) array

/*** 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--; }        }    }

(2) One-way linked list

classSolution { Public: ListNode*insertionsortlist (ListNode *head) {ListNode* newhead=nullptr; ListNode* toinsert=Head;  while(toinsert!=nullptr) {ListNode* current=Newhead; ListNode* last=nullptr; ListNode* next=toinsert->Next;  while(current!=nullptr&&current->val<=toinsert->val) { Last=Current ; Current=current->Next; }            //smaller than any sorted number, insert the head            if(last==nullptr) {Toinsert->next=Newhead; Newhead=Toinsert; }            //The middle or tail insertion method of the linked list is consistent            Else{Toinsert->next=last->Next; Last->next=Toinsert; } Toinsert=Next; }        returnNewhead; }};

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 three most basic algorithms in the sorting algorithm (simple selection, bubbling, inserting), the time complexity of the three sorting algorithms are O (n2)

Graphical sorting algorithm (i) 3 simple sort (selection, bubbling, direct insertion)

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.