Write a function partition (), that take the first element of the array x and put x in a position such
that all smaller elements (smaller than x) are before x, and put all greater elements (greater than
x) after x.
#include <iostream>
using namespace std;
//Write a function partition (), that take the first element of the array x and put x in a position such
//that all smaller elements (smaller than x) are before x, and put all greater elements (greater than x) after x.
void partition(int values[]){
int li=1;Â
int ri=14;
int x = values[0];
int temp;
while (li<ri){
while (values[li]<=x){
li++;
}
while (values[ri]>= x){
ri--;
}
if (li<ri){
temp = values[li];
values[li] = values[ri];
values[ri]= temp;
li++;Â
ri--;
}
}
temp = values[li-1];
values[li-1]=x;
values[0]=temp;
}
//main method
int main(){
int values[15]={15,65,18,14,19,16,18,17,12,13,12,7,16,13,16};
cout<<"Values: ";
for(int i=0;i<15;i++){
cout<<values[i]<<" ";
}
partition(values);
cout<<"\n\nPartition\n";
cout<<"\nValues: ";
for(int i=0;i<15;i++){
cout<<values[i]<<" ";
}
cout<<"\n\n";
system("pause");
return 0;
}
Comments
Leave a comment