Wednesday, November 27, 2019

Partitioning An Array in C++

What is meant partitioning:
The array would have smaller and larger values separated by a specific value.

example:
if the array is:  5 | 4 | 1| 7 | 3  and we want it to partition at value 5;
larger value is 7, goes after 5;
smaller values are 1, 4 and 3; goes before 5

The final output after partitioning would be:  4 | 1 | 3| 5 | 7
What is not taken into account in here, is, we are NOT doing any kind of sorting over here. We are just setting up a boundary of data where the rest of values gets separated.



Partitioning an array: Pseudo

  1. Take a carbon Copy of the array 
  2. Make the main array become all value = partition value 
  3. Iterate an compare with smaller number and larger numbers 
  4. Smaller numbers gets to go in the front indexes of  the array
  5. Larger number gets to go in the back indexes of the array
  6. While iterating, we don't worry about value being the same as partition
  7. Rest of the array remains as the partition value.
Task: Write a function that would take three parameters:  a double array, an int representing the array size, indx representing the partition value index

Here's the C++ code:

void Partition(double data[],int n, int indx)
{
cout <<"\n=======================================================\n";
double tempData[n]; //a carbon copy of the input array
for (int i=0; i<n; i = i+1)
{
tempData[i]=data[i];
}
for (int i=0; i<n; i = i+1) {cout<< tempData[i]<<"|"; } //print array
cout<<"\n";

int boundary=data[indx];
cout << "Partition is at : "<<boundary<<endl;

for (int i=0; i<n; i = i+1) {data[i]=boundary;} //main array is all now.

 for (int i=0,j=0,k=n-1; i<=n-1 ; i++)  //i to iterate, j to count from front, k to count from back
    {
if (tempData[i] < boundary) //if the value is less than the boundary 
{
cout <<"\n";
data[j] = tempData[i] ;  //add it to the front
j++;
for (int m=0; m<5; m = m+1) {cout<< data[m]<<"|"; }
cout<<"\n";
}
else if (tempData[i] > boundary) //if the value is more than the boundary 
{
data[k] = tempData[i] ; //add it to the back
k--;
for (int m=0; m<5; m = m+1) {cout<< data[m]<<"|"; }
cout<<"\n";
}
//if any iterate value is matching the boundary, we do nth now, the iterated value would remain 0
}

cout<< "\n\n";
for (int i=0; i<5; i = i+1) {cout<< data[i]<<"|"; } //print array
cout <<"\n=======================================================\n";
return;
}

Ashikur Rahman

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation.

0 comments:

Post a Comment

 

Copyright @ 2017 Codename: CPlusPlus.

Designed by Templateiy