ALGORITHM Quicksort(A[l..r])
//Sorts a subarray by quicksort
//Input: Subarray of array A[0..n - 1], defined by its left and right
// indicesl and r
//Output: Subarray A[l..r] sorted in nondecreasing order
if l < r
s ←Partition(A[l..r]) //s is a split position
Quicksort(A[l..s - 1])
Quicksort(A[s + 1..r])
ALGORITHM Partition(A[l..r])
//Sorts a subarray by quicksort
//Input: Subarray of array A[0..n - 1], defined by its left and right
// indicesl and r
//Output: Subarray A[l..r] sorted in nondecreasing order
if l < r
s ←Partition(A[l..r]) //s is a split position
Quicksort(A[l..s - 1])
Quicksort(A[s + 1..r])
ALGORITHM Partition(A[l..r])
//Partitions a subarray by Hoare’s algorithm, using the first element
// as a pivot
//Input: Subarray of arrayA[0..n - 1], defined by its left and right
// indicesl and r (l < r)
// as a pivot
//Input: Subarray of arrayA[0..n - 1], defined by its left and right
// indicesl and r (l < r)
//Output: Partition of A[l..r], with the split position returned as
// this function’s value
// this function’s value
p ← A[l]
i ← l;
j ← r + 1
repeat
repeat i ← i + 1 until A[i] ≥ p
repeat j ← j - 1 until A[j] ≤ p
swap(A[i], A[j])
until i ≥ j
swap(A[i], A[j]) //undo last swap when i ≥ j
swap(A[l], A[j])
return j
C program:
#include<stdio.h>
void quicksort(int number[25],int first,int last){
int i, j, pivot, temp;
if(first<last){
pivot=first;
i=first;
j=last;
while(i<j){
while(number[i]<=number[pivot]&&i<last)
i++;
while(number[j]>number[pivot])
j--;
if(i<j){
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
temp=number[pivot];
number[pivot]=number[j];
number[j]=temp;
quicksort(number,first,j-1);
quicksort(number,j+1,last);
}
}
int main(){
int i, count, number[25];
printf("How many elements are u going to enter: ");
scanf("%d",&count);
printf("Enter %d elements: ", count);
for(i=0;i<count;i++)
scanf("%d",&number[i]);
quicksort(number,0,count-1);
printf("Order of Sorted elements: ");
for(i=0;i<count;i++)
printf(" %d",number[i]);
return 0;
}
Output:
How many elements are u going to enter: 5
Enter 5 elements: 2
3
1
8
4
Order of Sorted elements: 1 2 3 4 8
C program:
#include<stdio.h>
void quicksort(int number[25],int first,int last){
int i, j, pivot, temp;
if(first<last){
pivot=first;
i=first;
j=last;
while(i<j){
while(number[i]<=number[pivot]&&i<last)
i++;
while(number[j]>number[pivot])
j--;
if(i<j){
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
temp=number[pivot];
number[pivot]=number[j];
number[j]=temp;
quicksort(number,first,j-1);
quicksort(number,j+1,last);
}
}
int main(){
int i, count, number[25];
printf("How many elements are u going to enter: ");
scanf("%d",&count);
printf("Enter %d elements: ", count);
for(i=0;i<count;i++)
scanf("%d",&number[i]);
quicksort(number,0,count-1);
printf("Order of Sorted elements: ");
for(i=0;i<count;i++)
printf(" %d",number[i]);
return 0;
}
Output:
How many elements are u going to enter: 5
Enter 5 elements: 2
3
1
8
4
Order of Sorted elements: 1 2 3 4 8
0 comments:
Post a Comment