2015-08-30 28 views
1

这里是我的代码:为什么我的快速排序实施不起作用?

#include<iostream> 
using namespace std; 

//Array that needs to be sorted 
int a[]={234,45,234,65,234,65,234,567,234,123,11,23,43,45,6,7,7,4,233,4,6,4,3,11,23,556,7,1,2,3,4,5,6,7,}; 

//Calculate the size of the array 
int n=sizeof(a)/sizeof(a[0]); 

//Swap utility function to swap two numbers 
void swap(int a,int b) 
{ 
     int t=a; 
     a=b; 
     b=t; 
} 

//Partion the array into two according to the pivot,i.e a[r] 
int partion(int p,int r) 
{ 
     int x=a[r],i=p-1; 
     for(int j=p;j<r;j++) 
      if(a[j]<=x) 
      { 
        i++; 
        swap(a[i],a[j]); 
      } 
     swap(a[r],a[i+1]); 
     return i+1; 
} 

//Recursive method to sort the array 
void quick_sort(int p,int r) 
{ 
     if(p<r) 
     { 
      int q=partion(p,r); 
      quick_sort(p,q-1); 
      quick_sort(q+1,r); 
     } 
} 

int main() 
{ 
     cout<<"\nOriginal array:\n"; 
     for(int i=0;i<n;i++) 
      cout<<a[i]<<" "; 
     cout<<endl; 
     quick_sort(0,n-1); 
     cout<<"Sorted array:\n"; 
     for(int i=0;i<n;i++) 
      cout<<a[i]<<" "; 
     cout<<endl; 
} 

它输出:

Original array: 
234 45 234 65 234 65 234 567 234 123 11 23 43 45 6 7 7 4 233 4 6 4 3 11 23 556 7 1 2 3 4 5 6 7 
Sorted array: 
234 45 234 65 234 65 234 567 234 123 11 23 43 45 6 7 7 4 233 4 6 4 3 11 23 556 7 1 2 3 4 5 6 7 

我不知道是什么问题。这是一个快速排序的实现错误还是数组'a []'或其他内容的范围中的错误。

数组'a []'是一个全局变量,所以我认为分区和快速排序对它进行操作。看起来阵列保持不变。

回答

1

看一看你的交换功能:

void swap(int a,int b) 
{ 
     int t=a; 
     a=b; 
     b=t; 
} 

它改变了复制变量的值。你想通过引用传递a和b,所以它们的值被改变。

void swap(int &a,int &b) 
{ 
     int t=a; 
     a=b; 
     b=t; 
} 
+0

它的工作原理。谢谢! –