#include <stdio.h>
#include <stdlib.h>
int swap(int &a, int &b);
int sorting(int *array, int &b, int &l);
int partition(int *array ,int &begin, int &last);
int main()
{
FILE* pFile=fopen("input.txt", "r");
//fopen("input.txt", "r");
//fopen("output.txt", "w");
int n;
int begin=0;
fscanf(pFile, "%d", &n);
int* array=(int*)malloc(n*sizeof(int));
for (int i=0; i<n; ++i)
fscanf(pFile,"%d", &array[i]);
int n1=n-1;
sorting(array, begin, n1);
printf("JJJJ");
for (int i=0; i<n; ++i)
printf("%d ", array[i]);
printf("\n");
fclose(pFile);
free(array);
return 0;
}
int sorting(int* array, int &b, int &l)
{
int pivot,pivot1;
if(b<l)
{
pivot=partition(array, b, l);
printf("MAXMAX321");
int a=pivot-1;
sorting(array, b, a);
printf("MAXMAX123");
pivot1=pivot+1;
sorting(array, pivot1, l);
printf("MAXMAX");
}
return 0;
}
int partition(int* array, int &b, int &l)
{
int x=array[b];
int i=b;
int j=l;
while(true)
{
while(array[j]>x){
printf("AHAH");
--j;
}
while(array[i]<x){
printf("AZAZA");
++i;
}
if(i<j)
swap(array[i],array[j]);
else
return j;
}
}
int swap(int &x, int &y)
{
x=x+y;
y=x-y;
x=x-y;
return 0;
}
提前谢谢。
答案 0 :(得分:1)
这部分是非常危险的代码:
while(true)
{
while(array[j]>x){
printf("AHAH");
--j;
}
while(array[i]<x){
printf("AZAZA");
++i;
}
if(i<j)
swap(array[i],array[j]);
else
return j;
}
while (true)
,除非在非常特殊的情况下,您应该在循环中说明明确的条件。这是导致“回归”的一个。它将阐明循环的目标。while(array[i]<x)
之类的数组值之前将i
与数组大小进行比较!您永远不确定阵列中是否始终满足您的条件,确保您有安全带。答案 1 :(得分:0)
我无法理解你在功能分区中做了什么,但这样做应该有效:
int partition(int* array, int &b, int &l)
{
int pivot_index = l;//You can take here everything between b and l
//swap(array[l], array[pivot_index]); decomment this if your pivot is between b and l
int current_pos = b;
for(int i = b;i < l - 1; ++i)
if(array[i] <= array[pivot_index])
swap(array[i], array[current_pos++]);
swap(array[l], array[current_pos]);
return current_pos;
}