{"id":25216,"date":"2017-10-15T15:43:50","date_gmt":"2017-10-15T10:13:50","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25216"},"modified":"2017-10-15T15:43:50","modified_gmt":"2017-10-15T10:13:50","slug":"cycle-sort","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/cycle-sort\/","title":{"rendered":"Cycle Sort"},"content":{"rendered":"<p>Cycle sort is an in-place sorting Algorithm, <a href=\"https:\/\/en.wikipedia.org\/wiki\/Sorting_algorithm#Stability\" target=\"_blank\" rel=\"noopener\">unstable sorting algorithm<\/a>, a comparison sort that is theoretically optimal in terms of the total number of writes to the original array.<\/p>\n<ul>\n<li>It is optimal in terms of number of memory writes. It <a href=\"http:\/\/www.geeksforgeeks.org\/which-sorting-algorithm-makes-minimum-number-of-writes\/\" target=\"_blank\" rel=\"noopener\">minimizes the number of memory writes<\/a> to sort (Each value is either written zero times, if it\u2019s already in its correct position, or written one time to its correct position.)<\/li>\n<li>It is based on the idea that array to be sorted can be divided into cycles. Cycles can be visualized as a graph. We have n nodes and an edge directed from node i to node j if the element at i-th index must be present at j-th index in the sorted array.<br \/>\nCycle in arr[] = {4, 5, 2, 1, 5}<\/li>\n<li>We one by one consider all cycles. We first consider the cycle that includes first element. We find correct position of first element, place it at its correct position, say j. We consider old value of arr[j] and find its correct position, we keep doing this till all elements of current cycle are placed at correct position, i.e., we don\u2019t come back to cycle starting point.\n<div id=\"practice\">\n<p>Recommended: Please try your approach on <b><i><u>{IDE}<\/u><\/i><\/b> first, before moving on to the solution.<\/p>\n<\/div>\n<p><strong>Explanation :<\/strong><\/p>\n<pre> arr[] = {10, 5, 2, 3}\r\n index =  0   1   2   3\r\ncycle_start = 0 \r\n<strong>item<\/strong> = 10 = arr[0]\r\n\r\nFind position where we put the item  \r\npos = cycle_start\r\nwhile (arr[i] &lt; item)  \r\n    pos++;\r\n\r\nWe put 10 at arr[3] and change item to \r\nold value of arr[3].\r\narr[] = {10, 5, 2, <strong><em>10<\/em><\/strong>} \r\n<strong>item<\/strong> = 3 \r\n\r\nAgain rotate rest cycle that start with <strong>index '0' <\/strong>\r\nFind position where we put the item = 3 \r\nwe swap item with element at arr[1] now \r\narr[] = {10, <strong><em>3<\/em><\/strong>, 2, <strong><em>10<\/em><\/strong>} \r\n<strong>item<\/strong> = 5\r\n\r\nAgain rotate rest cycle that start with index '0' and item = 5 \r\nwe swap item with element at arr[2].\r\narr[] = {10, <strong><em>3<\/em><\/strong>, <strong><em>5<\/em><\/strong>, <strong><em>10<\/em> <\/strong>} \r\n<strong>item<\/strong> = 2\r\n\r\nAgain rotate rest cycle that start with index '0' and item = 2\r\narr[] = {<strong><em>2<\/em><\/strong> ,<strong><em>3<\/em><\/strong> ,<strong> <em>5<\/em><\/strong>, <strong><em>10<\/em><\/strong>}  \r\n\r\nAbove is one iteration for cycle_stat = 0.\r\nRepeat above steps for cycle_start = 1, 2, ..n-2<\/pre>\n<p>&nbsp;<\/p>\n[ad type=&#8221;banner&#8221;]<\/li>\n<li><strong>Below is C++ implementation of above Cycle Sort.<\/strong><\/li>\n<\/ul>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">C++<\/span> <\/div> <pre class=\"language-cpp code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-cpp code-embed-code\">\/\/ C++ program to impleament cycle sort<br\/>#include &lt;iostream&gt;<br\/>using namespace std;<br\/> <br\/>\/\/ Function sort the array using Cycle sort<br\/>void cycleSort (int arr[], int n)<br\/>{<br\/>    \/\/ count number of memory writes<br\/>    int writes = 0;<br\/> <br\/>    \/\/ traverse array elements and put it to on<br\/>    \/\/ the right place<br\/>    for (int cycle_start=0; cycle_start&lt;=n-2; cycle_start++)<br\/>    {<br\/>        \/\/ initialize item as starting point<br\/>        int item = arr[cycle_start];<br\/> <br\/>        \/\/ Find position where we put the item. We basically<br\/>        \/\/ count all smaller elements on right side of item.<br\/>        int pos = cycle_start;<br\/>        for (int i = cycle_start+1; i&lt;n; i++)<br\/>            if (arr[i] &lt; item)<br\/>                pos++;<br\/> <br\/>        \/\/ If item is already in correct position<br\/>        if (pos == cycle_start)<br\/>            continue;<br\/> <br\/>        \/\/ ignore all duplicate  elements<br\/>        while (item == arr[pos])<br\/>            pos += 1;<br\/> <br\/>        \/\/ put the item to it&#039;s right position<br\/>        if (pos != cycle_start)<br\/>        {<br\/>            swap(item, arr[pos]);<br\/>            writes++;<br\/>        }<br\/> <br\/>        \/\/ Rotate rest of the cycle<br\/>        while (pos != cycle_start)<br\/>        {<br\/>            pos = cycle_start;<br\/> <br\/>            \/\/ Find position where we put the element<br\/>            for (int i = cycle_start+1; i&lt;n; i++)<br\/>                if (arr[i] &lt; item)<br\/>                    pos += 1;<br\/> <br\/>            \/\/ ignore all duplicate  elements<br\/>            while (item == arr[pos])<br\/>                pos += 1;<br\/> <br\/>            \/\/ put the item to it&#039;s right position<br\/>            if (item != arr[pos])<br\/>            {<br\/>                swap(item, arr[pos]);<br\/>                writes++;<br\/>            }<br\/>        }<br\/>    }<br\/> <br\/>    \/\/ Number of memory writes or swaps<br\/>    \/\/ cout &lt;&lt; writes &lt;&lt; endl ;<br\/>}<br\/> <br\/>\/\/ Driver program to test above function<br\/>int main()<br\/>{<br\/>    int arr[] = {1, 8, 3, 9, 10, 10, 2, 4 };<br\/>    int n = sizeof(arr)\/sizeof(arr[0]);<br\/>    cycleSort(arr,  n) ;<br\/> <br\/>    cout &lt;&lt; &quot;After sort : &quot; &lt;&lt;endl;<br\/>    for (int i =0; i&lt;n; i++)<br\/>        cout &lt;&lt; arr[i] &lt;&lt; &quot; &quot;;<br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p>utput:<\/p>\n<pre>1 3 4 8 10 10 \r\n<\/pre>\n<p><strong>Time Complexity<\/strong> : O(n<sup>2<\/sup>)<br \/>\nWorst Case : O(n<sup>2<\/sup>)<br \/>\nAverage Case: O(n<sup>2<\/sup>)<br \/>\nBest Case : O(n<sup>2<\/sup>)<\/p>\n<p>This sorting algorithm is best suited for situations where memory write or swap operations are costly.<\/p>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Cycle Sort &#8211; Searching and sorting &#8211; Cycle sort is an in-place sorting Algorithm,unstable sorting algorithm, a comparison sort that is theoretically optimal in terms of the total number of writes to the original array<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1,83508,71670],"tags":[70030,72197,70892,72177,71121,71135,72174,72205,71146,72176,72199,72183,72172,72203,72196,72201,71144,70895,70969,72186,72189,72182,70075,72191,72179,72181,72180,72184,72178,72200,72204,72202,72198,70718,72173,71175,71695,70020,71161,71149,70967,71156,72187,71142,72190,71159,72195,72185,72175,72188,70759,72192,72194,72193],"class_list":["post-25216","post","type-post","status-publish","format-standard","hentry","category-coding","category-cycle-sort","category-searching-and-sorting","tag-all-sorting-algorithms","tag-best-sorter","tag-best-sorting-algorithm","tag-best-sport","tag-bubble-sort-algorithm","tag-bubble-sort-algorithm-in-data-structure","tag-cell-cycle","tag-cell-cycle-facs","tag-comparison-of-sorting-algorithms","tag-cube-formula","tag-curly-extensions","tag-cx-x","tag-cycle-cycle","tag-cycle-flower","tag-cycling-thermals","tag-cyclone-ii","tag-different-sorting-algorithms","tag-fastest-sorting-algorithm","tag-java-sorting-algorithms","tag-life-cycle-of-a-plant","tag-life-cycle-of-flowering-plants","tag-life-cycle-of-plants","tag-linear-sort","tag-list-sort","tag-phases-of-cell-cycle","tag-plant-cycle","tag-plant-life","tag-plant-life-cycle","tag-plant-life-cycle-for-kids","tag-plant-life-cycle-for-preschool","tag-plant-life-cycle-preschool","tag-plants-and-life","tag-plants-for-life","tag-searching-and-sorting-algorithms","tag-sickle-cell","tag-sort-example","tag-sorted","tag-sorting-algorithms","tag-sorting-algorithms-comparison","tag-sorting-algorithms-in-data-structures","tag-sorting-algorithms-java","tag-sorting-algorithms-with-examples","tag-sorting-and-searching-algorithms","tag-sorting-in-data-structure","tag-sorting-methods","tag-sorting-program","tag-sorting-types","tag-sortings","tag-sport-bike","tag-testosterone-cycle","tag-topological-sort","tag-topological-sort-algorithm","tag-topological-sort-example","tag-visual-algo"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25216","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=25216"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25216\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=25216"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25216"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25216"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}