排序算法之0-1、0-1-2排序

之前碰到个非常有意思的题目,是关于排序算法的题目:

已知:一个数组:array,数组元素:0或1或2

求解:将数组按照0-1-2排序?

 

  1 template <class T>
  2 void Swap(T& t1, T& t2)
  3 {
  4     T tmp = t1;
  5     t1 = t2;
  6     t2 = tmp;
  7 }
  8 
  9 // Sorting a array which the elements are 0 or 1.
 10 void SortArray_0_1(int* arr, int n)
 11 {
 12     int first = 0;      // point to 0.
 13     int last = n - 1;   // point to 1.
 14 
 15     while (first < last)
 16     {
 17         // Find the position of first 0.
 18         while (0 == arr[first])
 19         {
 20             first++;
 21         }
 22 
 23         // Find the position of first 1.
 24         while (1 == arr[last])
 25         {
 26             last--;
 27         }
 28 
 29         if (first <= last && 1 == arr[first] && 0 == arr[last])
 30         {
 31             Swap(arr[first], arr[last]);
 32             first++;
 33             last--;
 34         }
 35     }
 36 }
 37 
 38 // Sorting a array which the elements are 0 or 1.
 39 void SortArray2_0_1(int* arr, int n)
 40 {
 41     //int first = 0;      // point to 0.
 42     int last = n - 1;   // point to 2.
 43     int k = 0;          // point to 1.
 44 
 45     while (k < last)
 46     {
 47         // Find 0.
 48         if (1 == arr[k])
 49         {
 50             while (1 == arr[last] && k < last)
 51             {
 52                 last--;
 53             }
 54 
 55             if (k < last)
 56             {
 57                 Swap(arr[k], arr[last]);
 58             }
 59         }
 60 
 61         if (0 == arr[k])
 62         {
 63             k++;
 64         }
 65     }
 66 }
 67 
 68 // Sorting a array which the elements are 0 or 1 or 2.
 69 void SortArry_0_1_2(int* arr, int n)
 70 {
 71     int first = 0;      // point to 0.
 72     int last = n - 1;   // point to 2.
 73     int k = 0;          // point to 1.
 74 
 75     while (k < last)
 76     {
 77         // Find 0.
 78         if (0 == arr[k])
 79         {
 80             while (0 == arr[first] && first < k)
 81             {
 82                 first++;
 83             }
 84 
 85             if (first < k)
 86             {
 87                 Swap(arr[k], arr[first]);
 88             }
 89         }
 90 
 91         // Find 1.
 92         if (1 == arr[k] || k == first)
 93         {
 94             k++;
 95         }
 96 
 97         // Find 2.
 98         if (2 == arr[k])
 99         {
100             while (2 == arr[last] && k < last)
101             {
102                 last--;
103             }
104 
105             if (k < last)
106             {
107                 Swap(arr[k], arr[last]);
108             }
109         }
110     }
111 }

 

posted @ 2015-04-16 19:30  nchxmoon  阅读(588)  评论(0编辑  收藏  举报