"Data structure" common 7 kinds of comparison sorting algorithm 2

Source: Internet
Author: User
Tags assert benchmark

Quick sorting (Quick sort)

1. Algorithm Description:

In the average condition, sort n data to be O (NLG (n)) times compared. In the worst-case scenario, an O (n^2) comparison is required, but this is not a common situation. In fact, fast sequencing is usually significantly faster than other O (NLG (n)) algorithms, because its internal loop (inner Loop) can be implemented efficiently on most architectures, and in most real-world data, it can determine the choice of design, The possibility of reducing the time required for two of the parties.

2. Steps:

1) Select an element from the series, called the "Datum" (pivot),

2) Reorder the series, where all elements are placed in front of the datum at a smaller value than the datum, and all elements are larger than the base value 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 partitioning operation.

3) Recursive Sorts a sub-column that is less than the base value element and a sub-column that is greater than the base value element.

Algorithm optimization:

1) If the sorting interval is small, the quick sort is less efficient and can be implemented by inserting sort

2) for the selection of the benchmark, using the three-digit method, it will not exactly take the maximum or minimum number, to avoid the fastest occurrence of the situation

Three-digit method (first, middle and end data)

Int getmidofthree (int *arr, int left, int mid, int right)//three-digit method (left, Mid and right data take the middle as "datum") { assert (arr); if  (Arr[left] < arr[mid])  {   if  (Arr[mid] < arr[right])   {   return arr[mid];   }  else //arr[right]<=arr[mid]  {   if  (arr[left]  > arr[right])     return arr[left];   else     return arr[right];  } } else//arr[left]>=arr[mid] {  if  (Arr[mid] > arr[right])   {   return arr[mid];  }   else//arr[right]>=arr[mid]  {   if  (Arr[right] > arr[left] )     return arr[left];   else    return arr[ Right];  }&nbsP;}} 

For step 2, there are three ways to implement

Int partsort1 (Int *arr, int left, int right)//method one {//so that the right is greater than the number of keys, the left is less than the number of keys  assert (arr);  int key = getmidofthree (arr, left, left -  (left  - right)  / 2, right)//select "Benchmark" subscript  //int key = arr[left];//can also be right  int begin = left; int end = right; while  (begin <  end)  {  while  (begin < end && arr[begin] <=  key)//From left to right to find a number greater than key   {   begin++;  }  while  (begin  < end && arr[end] >= key)//From right to left to find less than key number   {    end--;  }  if  (begin < end)//If the begin<end is exchanged, the equivalence can also be exchanged, so the if condition can not be written   {   swap (Arr[begin], arr[end]);   } } //at this time begin and end equal   if  (Arr[begin] >  arr[right])//Processing only two Eg:2 1; {  swap (Arr[begin], arr[right]); }  Return end;} Int partsort2 (Int *arr, int left, int right)//Method Two: Dig Pit method { assert (arr);  // The datum is left data, the right side is searched in the loop, then the search on the other side is done, the opposite is the order of the  //, so that the number larger than key can be stored in the previous part, smaller than the key is stored in the latter part  //can not use the three-digit method to select the benchmark " Only personal opinions, such as mistakes, please advise " int key = arr[left]; int begin = left; int  end = right;//here start at right  while  (begin < end)  {  while  ( Begin < end && arr[end] >= key)//on the right to find than Arr[key] small data   {    end--;  }  if  (begin < end)   {    arr[begin++] = arr[end];  }  while  (begin < end  && arr[begin] <= key)//left to find bigger than Arr[key] data   {   begin++;   }  if  (begin < end)//Buried pit. (end--) dig a new pit   {   arr[end--] = arr[begin];  } } arr[begin ] = key; return end;} INT&NBSP;PARTSORT3 (Int *arr, int left, int right)//Method Three: This method is better (code simple), through prev and cur traversal once to sort { int key = arr[right];//cannot be used in three-count, if key is Arr[left], the loop proceeds from the back, looking for a number greater than key to Exchange  int  prev = left - 1; int cur = left; while  (cur <  right)//the number that is greater than or equal to the key, jumps over, and encounters a number less than key stop to exchange  {//prev two cases: 1, immediately following the Cur; 2, pointing to the previous number larger than key   if  ( Arr[cur] < key && ++prev != cur)//If Prev and cur are not exchanged immediately   {    swap (Arr[cur], arr[prev]);   }  cur++; } swap (Arr[++prev],  arr[right]);//convert the latter of prev to the last element  return prev;}

Implementation of recursive function

void QuickSort (int *arr, int left, int. right) {assert (arr), if (left >= right)//recursive exit condition {return;} if (Right-left &L T 13)//When interval comparison hours, with insert sort (improve performance) {Insertsort (arr, right-left);}//int div = PartSort1 (arr, left, right); int div = PartSort2 (arr, left, right); int div = PARTSORT3 (arr, left, right); QuickSort (arr, left, Div-1); QuickSort (arr, div + 1, right);}

non-recursive implementation quick sort

VOID&NBSP;QUICKSORT_NONR (int *arr, int left, int right)//fast Sort---non-recursive method (using stack) {  ASSERT (arr); stack<int> s; if  (left < right)//end data into the stack, right first into the stack, left back into the stack  {  s.push (right),   s.push (left); } while  (left < right  && !s.empty ())  {  //Remove both ends of the data segment to be   left = s.top ();   s.pop ();   right = s.top ();   s.pop ();  if  (left -  right < 13)   {   insertsort (arr, left - right + &NBSP;1);   }  else  {      int div =  partsort3 (arr, left, right);//loop, div right after the stack, first to the right of the sort    if  (left <  div - 1)    {    s.push (div - 1);     s.push (left);    }   if  (right > div + 1)    {     s.push (right);     s.push (div + 1);    }  }  }}

Merge sort (Merg sort)

1. Algorithm Description:

Merge sort is an effective way to set up a merge operation . Sort algorithm . This algorithm is A very typical application of the method of division and treatment.

2. Steps:

1) apply as large a space as the original sequence, which is used to store the merged sequence

2) The sequence is divided into two parts, recursive, so that the small sequence in order, in the fallback to make a larger sequence order

3) After merging two sequences, write the ordered sequence back to the original sequence.


Void _merg (int *arr, int *tmp, int begin1, int end1, int  BEGIN2,&NBSP;INT&NBSP;END2)//two-sequence merge { assert (arr);  assert (TMP); int index =  begin1; while  (Begin1 <= end1 && begin2 <= end2)  {   if  (arr[begin1] < arr[begin2])//Small Data write tmp  {   tmp[ index] = arr[begin1];   begin1++;  }  else  {    tmp[index] = arr[begin2];   begin2++;  }  index++;  } //data Multi-sequence link at TMP back  while  (BEGIN1&NBSP;&LT;=&NBSP;END1)  {  tmp[index++]  = arr[begin1++]; } while  (Begin2 <= end2)  {  tmp[index++ ] = arr[begin2++]; }}void _mergsort (Int *arr, int *tmp, int left,  int right)//recursive make mergingSequence of sequential calls to the merge sequence function { assert (arr);  assert (TMP); if  (left >= right)  {   return; } int mid = left -  (left - right)  / 2;  _mergsort (Arr, tmp, left, mid);  _mergsort (Arr, tmp, mid + 1,  right);  //merge and write back to arr  _merg (arr, tmp, left, mid, mid + 1,  right); for  (int i = left; i <= right; i++)  {   Arr[i] = tmp[i]; }}void mergsort (int *arr, int size) { assert (arr);  int *tmp = new int[size];//Open size space tmp temporary storage partially merged data  memset (tmp, 0, size *sizeof (int));//Initialize  _mergsort (arr, tmp, 0, size - 1);  delete[] tmp;}

This article is from the "Scen" blog, make sure to keep this source http://10741357.blog.51cto.com/10731357/1775880

"Data structure" common 7 kinds of comparison sorting algorithm 2

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.