# C++-关于快速排序的一个C语言问题

`void print(int *a, int len){    for(int i = 0; i < len; i++)        cout << a[i] << ' ';    cout << endl;}void quickSort(int *a, int first, int last){    if(first >= last)        return ;        int pos = a[last];    int j;    for(int i = first, j = first; i < last; i++)    {        if(a[i] <= pos)            swap(a[i], a[j++]);    }    cout << "j = " << j << endl;    swap(a[j], a[last]);    print(a, last - first + 1);}int main(){    int b[] = {1, 5, 2, 4, 3};    int len_b = sizeof b / sizeof b[0];    quickSort(b, 0, len_b - 1);    print(b, len_b);}`

### 评论（3）

2017-10-18 3 楼
```#include <iostream>
using namespace std;

void print(int *a, int len)
{
for(int i = 0; i < len; i++)
cout << a[i] << ' ';
cout << endl;
}

void quickSort(int *a, int first, int last)
{
if(first >= last)
return;

int pos = a[last];
int j;                                //这里声明了j但是未初始化
//  int i;
//for里i前加了int表示声明了局部变量i和j，初值是first，这个仅仅是for局部变量，跟上面的j无关
for(int i = first , j = first; i < last; i++)
{
if(a[i] <= pos)
swap(a[i], a[j++]);
}
//所以出了for后j还是一个未初始化的值
cout << "j = " << j << endl;
swap(a[j], a[last]);
print(a, last - first + 1);
}

int main()
{
int b[] = {1, 5, 2, 4, 3};
int len_b = sizeof b / sizeof b[0];
quickSort(b, 0, len_b - 1);
print(b, len_b);
return 0;
}```

2017-03-29 2 楼

2017-03-21 1 楼

int j;
for(int i = first, j = first; i < last; i++)
{
if(a[i] <= pos)
swap(a[i], a[j++]);
}
cout << "j = " << j << endl;

1858 主题
5737 回复
21542 人气