Implementation of some basic sorting algorithms and sorting algorithms

Source: Internet
Author: User

Implementation of some basic sorting algorithms and sorting algorithms

It took some time to implement nine basic sorting algorithms at a time,

Including:

[Bubble Sorting], [directly select sorting], [directly insert sorting ],

[Hill sorting], [Semi-insertion sorting], [quick sorting ],

[Heap sorting], [tournament sorting], and [Merge Sorting ].


Array is used for storage, and elements can be custom types that support heavy-load operators,

You can directly copy elements in the array, or use the index array to record the elements in the intermediate process.

Index sequence, but the final results are saved in the original array,

Okay, you don't need to talk about it anymore. go directly to the source code!


// Sort. h

/* ------------------------------------ [Description]: some sorting algorithms (Sort. h) Created by Beyond ray, 2015.1 ------------------------------------- */# ifndef H_SORT # define H_SORT # include <cassert> # include <functional> # include "WinnerTree. h "/* = all are from small to large =============================================== */ // --------------------------------- // Desc: exchange element // --------------------------------- template <typename T> void Swap (T & a, T & B) {T temp = a; a = B; B = temp;} // ------------------------------ // Desc: Bubble sorting, O (n ^ 2) // ------------------------------ template <typename T> void BubbleSort (T arr [], int left, int right) {assert (left> = 0 & right> = left); bool bChanged = false; for (int I = left; I <right; I ++) {bChanged = false; for (int j = right; j> = I + 1; j --) {if (arr [j] <arr [j-1]) {Swap (arr [j], arr [j-1]); bChanged = tr Ue ;}} if (! BChanged) break ;}/// ------------------------------- // Desc: Select sort directly, O (n ^ 2) // sort template <typename T> void ChooseSort (T arr [], int left, int right) {assert (left> = 0 & right> = left); for (int I = left; I <right; I ++) {int minIndex = I; for (int j = I + 1; j <= right; j ++) {if (arr [j] <arr [minIndex]) {minIndex = j ;}} if (minIndex! = I) Swap (arr [minIndex], arr [I]) ;}// -------------------------------- // Desc: insert directly for sorting, O (n ^ 2) // -------------------------------- template <typename T> void InsertSort (T arr [], int left, int right) {assert (left> = 0 & right> = left ); for (int I = left + 1; I <= right; I ++) {for (int j = left; j <= I-1; j ++) {if (arr [I] <arr [j]) {auto insertEle = arr [I]; for (int k = I; k> = j + 1; k --) {arr [k] = arr [k-1];} arr [J] = insertEle; break; }}}// ----------------------------------------------- // Desc: Hill sorting, O (nlogn) // ------------------------------------------- template <typename T> void ShellSort (T arr [], int left, int right, std: function <int (int)> & gapFunc) {assert (left> = 0 & right> = left); int gap = right-left + 1; while (gap! = 1) {gap = gap func (gap); for (int I = left; I <= right-gap; I ++) {int iCompareIdx = I + gap; if (arr [I]> arr [iCompareIdx]) {Swap (arr [I], arr [iCompareIdx]) ;}}// --------------------------------------/Desc: semi-insert sorting, O (nlogn) // -------------------------------------------- template <typename T> void BinaryInsertSort (T arr [], int left, int right) {assert (left> = 0 & right> = left); for (int I = left + 1; I <= right; I ++) {int iLeft = left, iRight = I-1, iCenter; while (iLeft <= iRight) {iCenter = (iLeft + iRight) /2; if (arr [I] <arr [iCenter]) iRight = iCenter-1; else if (arr [I]> arr [iCenter]) iLeft = iCenter + 1; else break;} // The Position of the iLeft record is the insert position. if (iLeft <= iRight) iLeft = iCenter + 1; // move the data in the future: auto insertEle = arr [I]; for (int j = I; j> = iLeft + 1; j --) {arr [j] = arr [j-1];} arr [iLeft] = insertEle ;}} // Rows // Desc: left, right, center arranged by Min, Max, and Mid // templates <typename T> T & ThreeSort_MinMaxMid (T arr [], int left, int right) {assert (left> = 0 & right> = left); int iCenter = (left + right)/2; int minIdx = left; // record the minimum index and switch it to the leftmost if (arr [iCenter] <arr [left]) minIdx = iCenter; if (arr [right] <arr [minIdx]) minIdx = righ T; if (minIdx! = Left) Swap (arr [left], arr [minIdx]); // switch the median to the right if (iCenter! = Right & arr [iCenter] <arr [right]) Swap (arr [iCenter], arr [right]); return arr [right];} // sort // Desc: Sort partitions in a quick sort // -------------------------------------------------- template <typename T> int Partition (T arr [], int left, int right) {T & lt; ThreeSort_MinMaxMid (arr, left, right); int iLeft = left, iRight = right-1; if (iLeft> iRight) return iLeft; while (1) {while (arr [iLef T] <= outer) iLeft ++; while (arr [iRight]> = outer) iRight --; if (iLeft> iRight) break; Swap (arr [iLeft], arr [iRight]);} // Swap the benchmark to the intermediate Swap (arr [iLeft], left); return iLeft;} // -------------------------------------------- // Desc: Fast sorting, O (nlogn) // ---------------------------------------------- template <typename T> void QuickSort (T arr [], int left, int right) {assert (left> = 0 & right> = left); int ipivot = Partition (ar R, left, right); if (ipivot-1> left) QuickSort (arr, left, ipivot-1); if (ipivot + 1 <right) QuickSort (arr, ipivot + 1, right);} // ------------------------------------------ // Desc: filter down // template <typename T> T & SiftDown (T arr [], int minIdx, int maxIdx) {int iFather = minIdx; int iLChild = 2 * iFather + 1; int iRChild = 2 * iFather + 2; int imaxEleIdx; while (iLChi Ld <= maxIdx) {// obtain two sub-elements (if (iRChild <= maxIdx & arr [iRChild]> arr [iLChild]) imaxEleIdx = iRChild; elseimaxEleIdx = iLChild; if (arr [iFather] <arr [imaxEleIdx]) {Swap (arr [iFather], arr [imaxEleIdx]); iFather = imaxEleIdx; iLChild = 2 * iFather + 1; iRChild = 2 * iFather + 2;} else break;} return arr [minIdx];} // else // Desc: heap sorting, O (nlogn )//------------------------------ -------------- Template <typename T> void HeapSort (T arr [], int maxIdx) {assert (maxIdx> = 0 ); // create the initial maximum heap for (int I = (maxIdx-1)/2; I> = 0; I --) {SiftDown (arr, I, maxIdx );} // construct the permutation sequence for (int I = maxIdx; I> 0; I --) {Swap (arr [0], arr [I]); SiftDown (arr, 0, i-1 );}} /* ===================================================== ========= the following sorting algorithms take into account the comparison of custom data types, in order to shorten the average time, we use the index method to record and finally copy the final result back to the array. ========================================================== ====== * // ---------------------------------------------------- // Desc: re-construct the original sorted array by index // ------------------------------------------------ template <typename T> void idxSort_Make (T arr [], int sortIdxArr [], int maxIdx) {assert (maxIdx> = 0); // [original array cyclic value assignment to construct the sorting sequence] T temp; // during replication, only one extra T space int I = maxIdx, tempIdx, lastSortIdx; bool bCircle = false; while (I>-1) {if (I! = SortIdxArr [I] & sortIdxArr [I]! =-1) // this element in the array has changed {// The first time it reaches the cycle point, the value of this position and the index number if (! BCircle) {temp = arr [I], tempIdx = I; bCircle = true; // in the loop} // if (sortIdxArr [I]! = TempIdx) {arr [I] = arr [sortIdxArr [I]; lastSortIdx = sortIdxArr [I]; sortIdxArr [I] =-1; I = lastSortIdx ;} else // loop end junction {arr [I] = temp; bCircle = false; sortIdxArr [I] =-1; I = tempIdx; while (I> 0 & sortIdxArr [-- I] =-1 );}} else // The position element remains unchanged after sorting {sortIdxArr [I --] =-1 ;}}// -------------------------------------------- // Desc: tournament sorting, O (nlogn) // -------------------------------------------- template <typename T> void T OurnamentSort (T arr [], int maxIdx) {assert (maxIdx> = 0); int * sortIdxArr = new int [maxIdx + 1]; if (sortIdxArr = nullptr) {cerr <"TournamentSort: An error occurred while allocating the Index Array Memory! "; Exit (1);} WinnerTree <T> wTree (maxIdx + 1); sortIdxArr [0] = wTree. init (arr); for (int I = 1; I <= maxIdx; I ++) {sortIdxArr [I] = wTree. getNewWinner () ;}// array reconstruction and clearing idxSort_Make (arr, sortIdxArr, maxIdx); delete [] sortIdxArr;} // ------------------------------------/Desc: merge two subsequences // ------------------------------------------ template <typename T> void TwoMerge (T arr [], int srcIdx [], int destIdx [], int left, Int center, int right) {int iSrc1Left = left, iSrc2Left = center + 1, iPos = left; // compare and copy the index number of the minor to the corresponding position of the Index Array while (iSrc1Left <= center & iSrc2Left <= right) destIdx [iPos ++] = arr [srcIdx [iSrc1Left] <= arr [srcIdx [iSrc2Left]? SrcIdx [iSrc1Left ++]: srcIdx [iSrc2Left ++]; // copy the remaining index number while (iSrc1Left <= center) destIdx [iPos ++] = srcIdx [iSrc1Left ++]; while (iSrc2Left <= right) destIdx [iPos ++] = srcIdx [iSrc2Left ++];} // merge // Desc: binary merge sorting, O (nlogn) // ------------------------------------------------ template <typename T> void TwoMerge_Sort (T arr [], int left, int right) {assert (left> = 0 & right> = left );//----- --------------------- // [Index Array allocation and initialization] // ---------------------------- // assign two index arrays int ilen = right-left + 1; int * sortIdx1 = new int [ilen]; if (sortIdx1 = nullptr) {cerr <"Merget_Sort: Index Array 1 memory allocation failed"; exit (1);} int * sortIdx2 = new int [ilen]; if (sortIdx2 = nullptr) {cerr <"Merget_Sort: Index Array 2 memory allocation failed"; exit (1 );} // initialize the index array for (int I = 0, j = left; I <ilen; I ++, j ++) {sortIdx1 [I] = j; sortIdx2 [I] = j ;}//----- --------------------- // [Index merging records] // ------------------------------ int k = 1, mid, end; // step k: 1, 2, 4, 8 ,.... bool bIdx1To2 = true; int iLOffset = 0, iROffset = right-left; while (k <ilen) {for (int beg = iLOffset; beg <iROffset; beg = end + 1) {mid = beg + k-1; end = mid + k; if (mid <iROffset & end> iROffset) end = iROffset; if (mid <iROffset) {if (bIdx1To2) TwoMerge (arr, sortIdx1, sortIdx2, beg, mid, en D); elseTwoMerge (arr, sortIdx2, sortIdx1, beg, mid, end) ;}// reverse bIdx1To2 =! BIdx1To2; k = 2 * k;} // ----------------------------- // [array reconstruction and Index Array cleaning] // ------------------------------- bIdx1To2? IdxSort_Make (arr, sortIdx1, iROffset): idxSort_Make (arr, sortIdx2, iROffset); delete [] sortIdx1; delete [] sortIdx2;} # endif

// WinnerTree. h

/* ------------------------------------- [Description]: WinnerTree used for sorting. h) Created by Beyond ray, 2015.1 bytes */# ifndef H_WINNER_TREE # define H_WINNER_TREEtemplate <typename T> class WinnerTree {public: WinnerTree (int sortNums );~ WinnerTree (); int init (T arr []); // initialize the winner tree (generate the first champion) int getNewWinner (); // get the new winner (remove the old winner) void coutWinnerTree (); // output winner tree (for debugging) private: T * m_Arr; // point to the int * m_Winner array to be sorted; // The index array of the winner tree (excluding the index-1) int m_SortNums; // The number of sorting (number of competitions)}; // constructor template <typename T> WinnerTree <T>:: WinnerTree (int sortNums): m_SortNums (sortNums) {assert (m_SortNums> 0); m_Winner = new int [2 * m_SortNums-1]; if (! M_Winner) {cerr <"The winner Tree Index Array Memory Allocation failed"; exit (1) ;}/// destructor template <typename T> WinnerTree <T> ::~ WinnerTree () {if (m_Winner) {delete [] m_Winner; m_Winner = NULL ;}// ------------------------- // Desc: initialize the winner tree // ------------------------- template <typename T> int WinnerTree <T>: init (T arr []) {m_Arr = arr; // initialize the contestant (Sorting Code) index sequence for (int I = m_SortNums-1, j = 0; I <= 2 * m_SortNums-2; I ++, j ++) m_Winner [I] = j; // construct the initialization winner tree int iLChild = 2 * m_SortNums-3; int iRChild = 2 * m_SortNums-2; for (int j = m_SortNums-2; J> = 0; j --) {if (arr [m_Winner [iLChild] <= arr [m_Winner [iRChild]) m_Winner [j] = m_Winner [iLChild]; elsem_Winner [j] = m_Winner [iRChild]; // mobile comparison index bit iLChild-= 2; iRChild-= 2;} return m_Winner [0];} // outputs // Desc: Output winner tree // ------------------------------------------ template <typename T> void WinnerTree <T >:: coutWinnerTree () {for (int I = 0; I <m_SortNums-1; I ++) {cout <m_Arr [m_Win Ner [I] <";}cout <endl ;}// ---------------------------------------- // After selecting the champion, select the new champion // ------------------------------------ template <typename T> int WinnerTree <T >:: getNewWinner () {// the first time the parent node value is overwritten, int offset = m_SortNums-1; int lastWinnerIdx = m_Winner [0] + offset; m_Winner [lastWinnerIdx] =-1; int nearIdx = lastWinnerIdx % 2 = 0? (LastWinnerIdx-1): (lastWinnerIdx + 1); int fatherIdx = (nearIdx-1)/2; m_Winner [fatherIdx] = m_Winner [nearIdx]; // always traverse to the root node to update the smallest winner while (fatherIdx! = 0) {fatherIdx = (fatherIdx-1)/2; int iLChild = 2 * fatherIdx + 1; int iRChild = 2 * fatherIdx + 2; if (m_Winner [iLChild] =-1) m_Winner [fatherIdx] = m_Winner [iRChild]; else if (m_Winner [iRChild] =-1) m_Winner [fatherIdx] = m_Winner [iLChild]; else {if (m_Arr [m_Winner [iLChild] <= m_Arr [m_Winner [iRChild]) m_Winner [fatherIdx] = m_Winner [iLChild]; elsem_Winner [fatherIdx] = m_Winner [iRChild] ;}} return m_Winner [0] ;}# endif

// Main. cpp

/* ----------------------------------- [Cpp file]: main. cpp Created by Beyond ray, 2015.1 ---------------------------------- */# include "Sort. h "# include <iostream> using namespace std; # include <time. h> const int ARR_NUMS = 15; int main (int argc, char * argv []) {srand (unsigned int) time (NULL); int a [ARR_NUMS]; std: function <int (int)> gapFunc = [] (int gap) {return (gap/3 + 1) ;}; for (int count = 0; count <9; count ++) {for (int I = 0; I <ARR_NUMS; I ++) {a [I] = rand () % 1000 ;} switch (count) {case 0: BubbleSort (a, 0, ARR_NUMS-1); cout <"BubbleSort:"; break; case 1: ChooseSort (a, 0, ARR_NUMS-1); cout <"ChooseSort:"; break; case 2: InsertSort (a, 0, ARR_NUMS-1); cout <"InsertSort:"; break; case 3: ShellSort (a, 0, ARR_NUMS-1, gapFunc); cout <"ShellSort:"; break; case 4: BinaryInsertSort (a, 0, ARR_NUMS-1 ); cout <"BinaryInsertSort:"; break; case 5: QuickSort (a, 0, ARR_NUMS-1); cout <"QuickSort:"; break; case 6: heapSort (a, ARR_NUMS-1); cout <"HeapSort:"; break; case 7: TournamentSort (a, ARR_NUMS-1); cout <"TournamentSort :"; break; case 8: TwoMerge_Sort (a, 0, ARR_NUMS-1); cout <"TwoMerge_Sort:"; break;} for (int I = 0; I <ARR_NUMS; I ++) {cout <a [I] <"" ;}cout <endl;} return 0 ;}

Result of a random number operation:


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.