Skip to content

Commit 79c3dda

Browse files
committed
sort questions
1 parent 90e05d6 commit 79c3dda

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed

Sort/WiggleSortSln.cs

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
/* ==============================================================================
2+
* 功能描述:WiggleSort
3+
* 创 建 者:gz
4+
* 创建日期:2017/5/31 14:02:01
5+
* ==============================================================================*/
6+
using System;
7+
using System.Collections.Generic;
8+
using System.Linq;
9+
using System.Text;
10+
11+
namespace WiggleSort
12+
{
13+
/// <summary>
14+
/// WiggleSort
15+
/// </summary>
16+
public class WiggleSortSln
17+
{
18+
private static int[] _array;
19+
20+
public int[] WiggleSort(int[] array)
21+
{
22+
_array = array;
23+
int median = findKThLargest(_array.Length / 2);
24+
int left = 0, i = 0, right = _array.Length - 1;
25+
26+
while (i <= right)
27+
{
28+
if (_array[newIndex(i)] > median)
29+
{
30+
//put newIndex(i) at odd index(from 1, 3, to 5, ...)
31+
swap(newIndex(left++), newIndex(i));
32+
i++;
33+
}
34+
else if (_array[newIndex(i)] < median)
35+
{
36+
//put newIndex(i) at even index(max even index to little .... )
37+
swap(newIndex(right--), newIndex(i)); //right--, so i relatively toward right 1 step
38+
}
39+
else
40+
{
41+
i++;
42+
}
43+
}
44+
return _array;
45+
}
46+
47+
private int newIndex(int index)
48+
{
49+
return (1 + 2 * index) % (_array.Length | 1);
50+
}
51+
52+
private void swap(int i, int j)
53+
{
54+
int tmp = _array[i];
55+
_array[i] = _array[j];
56+
_array[j] = tmp;
57+
}
58+
59+
//based on quick sort to find the Kth largest in _array
60+
private int findKThLargest(int k)
61+
{
62+
int left = 0;
63+
int right = _array.Length - 1;
64+
while (true)
65+
{
66+
int pivotIndex = quickSort(left, right);
67+
if (k == pivotIndex)
68+
return _array[pivotIndex];
69+
else if (k < pivotIndex)
70+
right = pivotIndex - 1;
71+
else
72+
left = pivotIndex + 1;
73+
}
74+
}
75+
76+
private int quickSort(int lo, int hi)
77+
{
78+
int key = _array[lo];
79+
while (lo < hi)
80+
{
81+
while (lo < hi && _array[hi] >= key)
82+
hi--;
83+
//hi is less than key, hi element moves to lo index
84+
_array[lo] = _array[hi];
85+
while (lo < hi && _array[lo] < key)
86+
lo++;
87+
//lo is bigger than key, lo element moves to hi index
88+
_array[hi] = _array[lo];
89+
}
90+
_array[lo] = key;
91+
return lo;
92+
}
93+
}
94+
}

0 commit comments

Comments
 (0)