-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathquickSortAlgorithm.cs
More file actions
96 lines (85 loc) · 3.13 KB
/
quickSortAlgorithm.cs
File metadata and controls
96 lines (85 loc) · 3.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace quickSortAlgorithm
{
/*
* code reference:
* https://shepherdyuan.wordpress.com/2014/08/03/sorting-algorithms/
*
* blog:
* http://juliachencoding.blogspot.ca/2015/06/3-way-partition-problem-dutch-national.html
*
* quick sort algorithm
*/
class Solution
{
static void Main(string[] args)
{
int[] A = { 1, 6, 2, 5, 4, 3 };
quickSort(A, 0, 5);
}
/*
* February 2, 2016
*
* How to design this recurisve fucntion?
* Sort array using quick sort
*
* Design tips and discussion:
* 1. First, remember using recursive function, divide and conquer
* 2. One array - for all the recursive function
* But each recursive will work on part of the array - left / right position
* 3. Remember how to do 2-way partition - how to choose pivot - how to use pivot point value to divide
* into 2 partitions - left side - smaller values, right side - bigger values
* 4. Partition -
* two pointers - one pointer is to iterate whole array, except pivot point
* second pointer - position of first node bigger than pivot value
*
* Actually, after the practice of February 2, 2016, Julia found out that two pointers can be designed much easy way:
* 1. First pointer - look for second partition part - right partition - start position
* 2. Second pointer - look for second partition part - right partition - end position
* and also, in partition process, in-place swap is used.
*
* Do not forget to swap second pointer value with pivot point value <-
* 5. Practice to write code using array - how to write code without a bug?
* 6. the output is stored in the input argument A[]
*
* Bug report:
* 1. still confuse the declaration: int[] A, not int A[] <- check C#
*/
public static void quickSort(int[] A, int left, int right)
{
if(left > right || left <0 || right <0) return;
int index = partition(A, left, right);
if (index != -1)
{
quickSort(A, left, index - 1);
quickSort(A, index + 1, right);
}
}
private static int partition(int[] A, int left, int right)
{
if(left > right) return -1;
int end = left;
int pivot = A[right]; // choose last one to pivot, easy to code
for(int i= left; i< right; i++)
{
if (A[i] < pivot)
{
swap(A, i, end);
end++;
}
}
swap(A, end, right);
return end;
}
private static void swap(int[] A, int left, int right)
{
int tmp = A[left];
A[left] = A[right];
A[right] = tmp;
}
}
}