가장 큰 숫자를 골라 뒤에 놓는 재귀 선택 정렬 함수를 작성하려고합니다. 나는 printf를 사용하여 무엇이 잘못되었는지 확인했고, "1 8 15 3 17 12 4 8 4"를 입력하면 for 루프 직전 8 번째 반복에서 멈 춥니 다. 세분화 오류가 발생합니다.
#include <stdio.h>
#include <stdlib.h>
void swap(int* ptr1, int* ptr2);
int selection_sort2(int A[], int n, int itr);
int
main(int argc, char* argv[]){
int temp_array[1000], counter=0, i, itr=0;
printf("Enter as many as 1000 values, ^D to end\n");
while(scanf("%d", &temp_array[counter]) == 1){
counter++;
}
printf("%d values read into array\n", counter);
printf("Before: ");
for(i=0; i<counter;i++){
printf("%4d", temp_array[i]);
}
printf("\n");
selection_sort2(temp_array, counter, itr);
return 0;
}
void swap(int* ptr1, int* ptr2){
int temp;
temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
}
int selection_sort2(int A[], int n, int itr){
int j,temp, max, i;
int itrs = itr;
printf("%d\n", n);
if(n==1){
printf("After2: ");
for(i=0; i<n+itrs;i++){
printf("%4d", A[i]);
}
return 1;
}
temp = A[n-1];
for(j=n-1;j>=0;j--){
printf("ok");
printf("what %d ", j);
if(A[j]>temp){
max = j;
temp = A[j];
}
}
if(max!= n-1){
swap(&A[n-1], &A[max]);
}
itrs++;
return selection_sort2(A,n-1,itrs);
}
원인은 초기화되지 않은 변수 max
이며 정렬 / 스왑을 중지 할시기를 결정하지 않는 것입니다.
배열이 이미 정렬되고 반복기가 1보다 크면 (이 경우 시간 n
값이 2가되고 배열이 이미 정렬되어 있음) if(A[j]>temp){
만족스럽지 않으므로 max
정크 값을 갖게되고 해당 정크 값이 문 아래에 표시됩니다. 호출되고 충돌이 발생합니다.
if(max!= n-1){
swap(&A[n-1], &A[max]);
}
충돌을 처리하는 솔루션
int swapped = 0
프로그램 시작 부분에 변수 를 취하고 swapped = 1
조건이 if(A[j]>temp){
충족 될 때 만듭니다 .
swap
상태를 다음과 같이 변경해야 합니다.if(swapped && max != n-1){
결론을 내리려면 다음 변경 사항을 수행해야합니다.
int j,temp, max, i, swapped = 0;
static int count = 0;
if(A[j]>temp)
{
max = j;
temp = A[j];
swapped = 1
}
// this will let you know the cause of the crash
printf("\n after %d iteration max = %d and temp =%d\n",++count,max,temp );
if(swapped && max != n-1)
{
swap(&A[n-1], &A[max]);
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다