Answer to Question #201356 in C++ for Harry

Question #201356

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.


1
Expert's answer
2021-05-31T16:36:29-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog