1、最后还是看了严版本的数据结构。。。加上测试发现错误不在指针,还是在循环逻辑上。。。
2、失败的代码(主要还是循环逻辑上的问题):
#include<stdio.h>
#include <stdlib.h>
void sort(int *a, int *left, int *right);
void main(){
//int s[] = { 1, 5, 8, 9, 9, 6, 9,10,11515,10,25};
int s[] = { 1, 1, 5, 0 };
int length = 4;
int *left;
left = &s[0];
int *right;
right = &s[length - 1];
sort(s, left, right);
for (int i = 0; i < length; i++){
printf("%d\n", s[i]);
}
system("pause");
}
//先使用快速排序 双指针
void sort(int *a, int *left, int *right){
int *p, *q;
p = left, q = right;
int tmp;
tmp = *p;
int *mid;
if (p == q){
return;
}
while (p != q){
while (*q >= tmp && p != q){
q--;
}
if (q != q){
*p = *q;
p++;
}
while (*p <= tmp && q != q){
p++;
}
if (q != q){
*q = *p;
q--;
}
printf("%d %d tmp\n",
p, q);
}
*p = tmp;
printf("%d tmp\n", tmp);
//存在问题的部分 画图解决
mid = p;
sort(a, left, mid);
sort(a, mid + 1, right);
/*
while (p != q){
if (*q >= tmp){
q--;
}
if (*p < tmp){
p++;
}
else{
//tmp2 = *p;
//*p = *q;
//*q = tmp2;
//p++;
*p = *q;
p++;
q = NULL;
}
}
printf("java");
*/
}
3、成功的代码:
#include<stdio.h>
#include <stdlib.h>
void sort(int *a, int *left, int *right);
void main(){
int s[] = { 1, 5, 8, 9, 9, 6, 9,10,11515,10,25};
//int s[] = { 1, 1, 5, 0 };
int length = 11;
int *left;
left = &s[0];
int *right;
right = &s[length - 1];
sort(s, left, right);
for (int i = 0; i < length; i++){
printf("%d\n", s[i]);
}
system("pause");
}
//先使用快速排序 双指针
void sort(int *a, int *left, int *right){
int *p, *q;
p = left, q = right;
// printf("%d\t%d\t%d\t%d", ++p, ++left, q, (right-2));
int tmp;
tmp = *p;
int *mid;
if (p < q){
while (p < q){
while (*q >= tmp && p < q){
q--;
}
*p = *q;
while (*p <= tmp && p < q){
p++;
}
*q = *p;
//printf("%d %d tmp\n",p, q);
}
*p = tmp;
// printf("%d tmp\n", tmp);
//存在问题的部分 画图解决
mid = p;
sort(a, left, mid-1);
sort(a, mid + 1, right);
}
/*
while (p != q){
if (*q >= tmp){
q--;
}
if (*p < tmp){
p++;
}
else{
//tmp2 = *p;
//*p = *q;
//*q = tmp2;
//p++;
*p = *q;
p++;
q = NULL;
}
}
printf("java");
*/
}