General Interview Algorithm summary--sorting algorithm (Java edition)

Source: Internet
Author: User

Sorting algorithms

Importance is self-evident, many algorithm problems often choose a good sorting algorithm often problems can be solved


1. Bubble Algorithm



Bubble sort (Bubble sort) is also a simple and intuitive sorting algorithm. It repeatedly visited the sequence to sort, comparing two elements at a time, and swapping them out if they were wrong in the order. The work of the sequence of visits is repeated until no more need to be exchanged, that is, the sequence is sorted. The algorithm is named because the smaller elements will slowly "float" through the switch to the top of the sequence. That's the problem with a double loop, but you need to be aware of the next frontier.

Algorithm steps:

1) compare adjacent elements. If the first one is bigger than the second one, swap them both.

2) for each pair of adjacent elements to do the same work, from the beginning of the first pair to the end of the last pair. When this is done, the final element will be the maximum number.

3) Repeat the above steps for all elements except the last one.

4) Repeat the above steps each time for less and fewer elements until there is no pair of numbers to compare.

<span style= "Font-family:microsoft yahei;font-size:14px;" >public void Bubblesort (int[] a) {int temp = 0;int len = a.length;for (int i = 0; i < len; i++) {for (int j = 1; J & Lt Len-i; J + +) if (A[j-1] > A[j]) {//attention to distinguish between a[j-1] or a[j] otherwise prone to boundary problems//from small to large sort temp = a[j-1];a[j-1] = a[j];a[j] = temp;}} </span>
optimized bubble sorting

Since it may have been sequenced in the first few times, it still needs to be traversed in the last bubble sort.

Optimization: Sets a flag that is true if the interchange occurred, otherwise false. Obviously if there was a trip without an exchange, the description sort has been completed.

<span style= "Font-family:microsoft yahei;font-size:14px;" >public void BubbleSort1 (int[] a) {int temp = 0;int len = A.length;boolean flag = true;while (flag) {flag = False;for ( int j = 1; J < Len-1; J + +) if (A[j-1] > A[j]) {//attention to distinguish between a[j-1] or a[j] otherwise prone to boundary problems//from small to large sort temp = a[j-1];a[j-1] = a[j];a[j] = temp;//Set flag bit FL AG = True;}}} </span>

2. Quick Sort

Quick sort is a sort of algorithm developed by Donny Holl. On average, sort n items to 0 (n log n) comparisons. In the worst case scenario, a 0 (N2) comparison is required, but this is not a common situation. In fact, fast sequencing is usually much faster than the other 0 (n log n) algorithms because its internal loop (inner Loop) can be implemented efficiently on most architectures.
Quick Sort uses the Divide and conquer strategy to divide a serial (list) into two sub-serial (sub-lists).

Algorithm steps:
1) Select an element from the sequence, called "Datum" (pivot),
2) reorder the series, all elements are placed in front of the datum with a smaller value than the Datum, and all the elements are placed behind the datum (the same number can be on either side). After the partition exits, the datum is in the middle of the sequence. This is called partition (partition) operation.
3) recursively (recursive) sorts sub-columns that are less than the base value element and sub-columns that are larger than the base value element. The bottom-most case of the
recursion is that the size of the sequence is 0 or one, which is always sorted. Although it is always recursive, the algorithm always exits, because in each iteration (iteration), it will at least put an element to its last position.

<span style= "Font-family:microsoft yahei;font-size:14px;" >private static void Quick_sort (int[] arr, int low, int. high) {//Resolve and merge if (low <= high) {int mid = partition (arr, lo W, high);//Recursive Quick_sort (arr, Low, mid-1); Quick_sort (arr, mid + 1, high);}}  private static int partition (int[] arr, int low, int. high) {//decomposition int pivot = Arr[high];int i = low-1;int temp;for (int J = Low; J < High; J + +) {if (Arr[j] < pivot) {i++;temp = Arr[i];arr[i] = arr[j];arr[j] = temp;}} Interchange intermediate elements and privottemp = arr[i + 1];arr[i + 1] = Arr[high];arr[high] = Temp;return i + 1;} </span>


3. Merge sort

The

Merge sort is an efficient sorting algorithm based on the merge operation. This algorithm is a very typical application of the partition method (Divide and Conquer).

Algorithm steps:

1. Apply the space to the sum of the two sorted sequences that are used to hold the merged sequence

2. Set two pointers, where the initial position is the starting position of two sorted sequences

3. Compare the elements pointed to by two pointers, select a relatively small element into the merge space, and move the pointer to the next position

4. Repeat step 3 until a pointer reaches the end of the sequence

5. Copy all remaining elements of another sequence directly to the end of the merge sequence

<span style= "Font-family:microsoft yahei;font-size:14px;"          > public static int[] Sort (int[] nums, int. Low, int.) {int mid = (low + high)/2;              if (Low < high) {//left sort (nums, low, mid);              Right sort (nums, mid + 1, high);          Merge merges Around (Nums, low, Mid, high);      } return nums;           public static void Merge (int[] nums, int. Low, int mid, Int. high) {int[] temp = new Int[high-low + 1];            int i = low;//left pointer int j = mid + 1;//right pointer int k = 0;                  Move the smaller number first to the new array while (I <= mid && J <= High) {if (Nums[i] < nums[j]) {              temp[k++] = nums[i++];              } else {temp[k++] = nums[j++];          }}//Move the left remaining number into the array while (I <= mid) {temp[k++] = nums[i++]; }//Move the remaining number in the right side into the array wHile (J <= High) {temp[k++] = nums[j++]; }//Overwrite the number in the new array with the Nums array for (int k2 = 0; K2 < temp.length; k2++) {nums[k2 + low] = temp[          K2]; }} </span>

4. Select Sort

Select sort (Selection sort) is also a simple and intuitive sorting algorithm.
Algorithm steps:
1) First find the smallest (large) element in the unordered sequence, and place it in the starting position of the sort sequence
2) continue to find the smallest (large) element from the remaining unsorted elements, and then place it at the end of the sorted sequence.
3) Repeat the second step until all the elements are sorted.

<span style= "Font-family:microsoft yahei;font-size:14px;" > Public  int[] Chosesort (int[] intarr) {for          (int i=0;i<intarr.length;i++) {              int lowindex = i;                            for (int j=i+1;j<intarr.length;j++) {                  if (Intarr[j]<intarr[lowindex]) {                      lowindex = j;                  }              }                            Swaps the current first element with the smallest element in the sequence after it, that is, placing the smallest element at the front-end              int temp = intarr[i];                         Intarr[i] = Intarr[lowindex];              Intarr[lowindex] = temp;          }                    return intarr;      } </span>

5. Heap sequencing

Heap ordering (heapsort) refers to a sort algorithm designed using the data structure of the heap. A heap is a structure that approximates a complete binary tree and satisfies the properties of the heap at the same time: that is, the key value or index of the child node is always less than (or greater than) its parent node.
The average time complexity for heap sorting is 0 (NLOGN).
Algorithm steps:
1) Create a heap h[0..n-1]
2) Swap the stack head (maximum) with the end of the heap
3) Reduce the size of the heap by 1 and call Shift_down (0) to adjust the new array top data to the corresponding position
4) Repeat step 2 until the size of the heap is 1

Tuning the heap section is not very good to write recommendations for reference http://blog.csdn.net/jdream314/article/details/6634863

Finally, a performance comparison chart of each algorithm is given.



Reference: http://www.cricode.com/3212.html

http://blog.csdn.net/morewindows/article/details/7961256


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

General Interview Algorithm summary--sorting algorithm (Java edition)

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.