Introduction
Quicksort is basically work on divide and conquer algorithm. Firstly quicksort divide the complete large array into small sub array, the low elements and the high elements. Quicksort also known as partition-exchange sort, use these steps:
- Choose any element of the array to be the pivot.
- Divide all others elements into two partition.
- All Elements less than the pivot must be first partition.
- All elements greater than the pivot must be the second partition.
- Use the recursion to sort both partition.
- Join the first sorted partition, the pivot, and the second sorted partition.
Algorithm
Quicksort(a,p,r)
- If p<r
- q=partition(a,p,r)
- Quicksort(a,p,q-1)
- Quicksort(a,q+1,r)
- Exit
Partition(a,p,r)
- X=a[r]
- I=p-1
- J=p to r-1
- Do if a[j]<=x
I=i+1
Exchange a[i]=a[j] - A[i+1]=a[j]
- Return i+1
Program
Now place the following code in you console app page:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace array
- {
- class Program
- {
- static public int partition(int[] item, int left, int right)
- {
- int pivot = item[left];
- while (true)
- {
- while (item[left] < pivot)
- left++;
-
- while (item[right] > pivot)
- right--;
-
-
- if (left < right)
- {
- int tem;
- tem = item[left];
- item[left] = item[right];
- item[right] = tem;
- }
- else
- {
- return right;
- }
- }
- }
- static public void quicksort(int [] arr,int left,int right)
- {
- if (left<right)
- {
- int pivot = partition(arr,left, right);
- if (pivot>1)
- {
- quicksort(arr,left,pivot-1);
- }
- if (pivot+1<right)
- {
- quicksort(arr,pivot+1,right);
- }
- }
- }
- static void Main(string[] args)
- {
- int [] item=new int[10];
- Console.WriteLine("Enter 10 Element");
- for (int i = 0; i < 10; i++)
- {
- item[i]=Int32.Parse(Console.ReadLine());
- }
- quicksort(item,0,10-1);
- Console.WriteLine("\nSorted Array :");
- for (int j = 0; j < 10; j ++)
- {
- Console.WriteLine(+item[j]);
- }
- Console.ReadLine();
- }
- }
- }
Output