开发者

partition of multidimensional array

开发者 https://www.devze.com 2023-04-03 01:21 出处:网络
i am trying to implement following algorithm: supposethere is array a[3][3],my aim is choose some pivotelement,for example a[1][1] and make partition suchthat, all element less then a[1][1] must be on

i am trying to implement following algorithm: suppose there is array a[3][3], my aim is choose some pivot element,for example a[1][1] and make partition such that, all element less then a[1][1] must be on开发者_Python百科 left side and above the pivot element, and all greater element on the right side and below pivot element. for example consider following matrix:

6 4 3
8 5 2
1 7 9

one of the possible partition of it is

3 4 6
2 5 7
1 8 9

as you see all less element are on the left side and above the pivot called 4. and others on the right side and below the pivot as 8. here is my code

#include <iostream>
using namespace std;
int main(){
  int a[3][3];
  for (int i=0;i<3;i++) {
    for (int j=0;j<3;j++){
      cin>>a[i][j];
    }
  }

  int i=0;
  int j=0;
  int n=2;
  int m=2;
  int pivot=a[1][1];

  while(  m>i && n>j) {
    while(a[m][n]>pivot)  --m;--n;
    while( a[i][j]<pivot) ++i;++j;

    int t=a[i][j];
    a[i][j]=a[m][n];
    a[m][n]=t;
  }

  for (int i=0;i<3;i++){
    for (int j=0;j<3;j++){
      cout<<a[i][j]<<"  ";
    }
    cout<<endl;
  }
  return 0;
}

but when i enter matrix above mentioned i got wrong result

6  5  3
8  4  2
1  7  9

please help me


I haven't looked if your algorithm is right, but when I see:

while(a[m][n]>pivot) --m;--n;

I think you meant:

while(a[m][n]>pivot) { --m;--n; }


Your problem as stated does not have a general solution. Specifically, there is no guarantee that all of the values less than the initial pivot value will fit to the left of the initial pivot point, nor that all of the values greater than the initial value will fit to the right of the initial pivot point.

You need to relax your requirements so that either the pivot value or the pivot location is allowed to change during the execution of the algorithm.

0

精彩评论

暂无评论...
验证码 换一张
取 消