Created
September 22, 2015 10:32
-
-
Save SteveBate/546be3877ee59bbd9861 to your computer and use it in GitHub Desktop.
Quicksort algorithm implementations in Go and C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
var numbers = new int[]{11, 3, 9, 15, 7, 6, 2, 1, 5, 23, 18, 4}; | |
Quicksort(numbers, 0, numbers.Length-1); | |
foreach(var n in numbers){ | |
Console.WriteLine(n); | |
} | |
} | |
public void Quicksort(int[] elements, int left, int right) | |
{ | |
int i = left, j = right; | |
int pivot = elements[(left + right) / 2]; | |
while (i <= j) | |
{ | |
while (elements[i] < pivot) | |
{ | |
i++; | |
} | |
while (elements[j] > pivot) | |
{ | |
j--; | |
} | |
if (i <= j) | |
{ | |
// Swap | |
int tmp = elements[i]; | |
elements[i] = elements[j]; | |
elements[j] = tmp; | |
i++; | |
j--; | |
} | |
} | |
// Recursive calls | |
if (left < j) | |
{ | |
Quicksort(elements, left, j); | |
} | |
if (i < right) | |
{ | |
Quicksort(elements, i, right); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
func main() { | |
numbers := []int{11, 3, 9, 15, 7, 6, 2, 1, 5, 23, 18, 4} | |
quicksort(numbers, 0, len(numbers)-1) | |
fmt.Println(numbers) | |
} | |
func quicksort(elements []int, left, right int) { | |
i, j := left, right | |
pivot := elements[(left+right)/2] | |
for i <= j { | |
for elements[i] < pivot { | |
i++ | |
} | |
for elements[j] > pivot { | |
j-- | |
} | |
if i <= j { | |
// Swap | |
elements[i], elements[j] = elements[j], elements[i] | |
i++ | |
j-- | |
} | |
} | |
// Recursive calls | |
if left < j { | |
quicksort(elements, left, j) | |
} | |
if i < right { | |
quicksort(elements, i, right) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment