I want to sort the data in a linked list by Quicksort . Here is my code:
struct stu
{
int id;
char name[100];
int score;
stu* next;
}head;
int address(stu* StudentList)
{
//return the index of data
int index = 0;
stu* test = head;
for (index = 0; test != StudentList; temp++)
{
test = test->next;
}
return index;
}
stu* section(int low)
{
//Classification discussion on data
stu* StudentList1=head;
for (int i = 0; i < low; i++)
{
StudentList1 = StudentList1->next;
}
return StudentList1;
}
void swap(stu *Student1,stu *Student2)
{
int t_id = 0, t_score = 0;
char t_name[10] = "000";
//exchange id
t_id = Student1->id;
Student1->id = Student2->id;
Student2->id = t_id;
//exchange name
strcpy(t_name, Student1->name);
strcpy(Student1->name, Student2->name);
strcpy(Student2->name, t_name);
//exchange score
t_score = Student1->score;
Student1->score = Student2->score;
Student2->score = t_score;
}
void sort(int low, int high)
{
stu* StudentList1 = head, * StudentList2 = StudentList1->next;
if (low >= high)
return;
else
{
StudentList1=section(low);
StudentList2 = StudentList1->next;
stu* key = StudentList1;
int i;
for (int i = 0; i <= (high - low) && StudentList2 != NULL; i++)
{
if (StudentList2->score >= key->score)
{
StudentList1 = StudentList1->next;
swap(StudentList1, StudentList2);
}
StudentList2 = StudentList2->next;
}
swap(key, StudentList1);
int temp = address(StudentList1);
StudentList2 = head;
for (i = 0; StudentList2->next!=NULL;StudentList2=StudentList2->next)
{
if (StudentList2->next->score <= StudentList2->score)
{
i++;
}
}
high = temp - 1;
low = temp + 1;
if (i < num - 1)
{
sort(0, high);
sort(low, num - 1);
}
return;
}
}
The problem is the The program is in a infinite loop . I tried to modify it but it didn't help . So I have to turn into Stackoverflow . Thank you !
I just modified my code . But there are still some problems . When processing 7 data , the program can run well . However , when processing 8 data , the compiler told me stack overflow in "section" . Hope that you can point out the problems . Thank you sincerely !