Last active
November 5, 2016 12:55
-
-
Save abdulateef/8a4a2ff739ce428f5250f0ad8513a75a to your computer and use it in GitHub Desktop.
Quicksort In-Place Solution in 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
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
class Solution { | |
static void Main(String[] args) | |
{ | |
int N = Convert.ToInt32(Console.ReadLine()); | |
string[] arr_temp = Console.ReadLine().Split(' '); | |
int[] list1 = Array.ConvertAll(arr_temp,Int32.Parse); | |
Solution.quickSortInPlace(list1); | |
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */ | |
} | |
public static void quickSortInPlace(int[] a) | |
{ | |
quickSortInPlace(a, 0, a.Length - 1); | |
} | |
public static void quickSortInPlace(int[] a , int first, int last) | |
{ | |
if((last - first) >= 1) | |
{ | |
int pivotposition = partition(a, first, last); | |
print(a); | |
quickSortInPlace(a, first, pivotposition - 1); | |
quickSortInPlace(a, pivotposition + 1, last); | |
} | |
} | |
public static int partition(int[] a, int first, int last) | |
{ | |
int pivot = a[last]; | |
int wallindex = first; | |
for(int currentindex = first; currentindex < last; ++currentindex ) | |
{ | |
if(a[currentindex] < pivot) | |
{ | |
swap(a, wallindex, currentindex); | |
++wallindex; | |
} | |
} | |
swap(a, wallindex, last); | |
return wallindex; | |
} | |
private static void print(int[] a) | |
{ | |
//Console.WriteLine(" "); | |
foreach(int element in a) | |
{ | |
print(element); | |
} | |
Console.WriteLine(" "); | |
} | |
public static void swap(int[] a, int indexA, int indexB) | |
{ | |
int temp = a[indexA]; | |
a[indexA] = a[indexB]; | |
a[indexB] = temp; | |
} | |
private static void print(int element) | |
{ | |
//Console.WriteLine(" "); | |
Console.Write(Convert.ToString(element) + " "); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment