2016-07-15 20 views
0

當我嘗試運行該程序時,收到消息。爲什麼?僅使用while對數組進行排序

Segmentation fault 

我的代碼:

#include <stdio.h> 

void sort_array(int *arr, int s); 

int main() { 
    int arrx[] = { 6, 3, 6, 8, 4, 2, 5, 7 }; 

    sort_array(arrx, 8); 
    for (int r = 0; r < 8; r++) { 
     printf("index[%d] = %d\n", r, arrx[r]); 
    } 
    return(0); 
} 

sort_array(int *arr, int s) { 
    int i, x, temp_x, temp; 
    x = 0; 
    i = s-1; 
    while (x < s) { 
     temp_x = x; 
     while (i >= 0) { 
      if (arr[x] > arr[i]) { 
       temp = arr[x]; 
       arr[x] = arr[i]; 
       arr[i] = temp; 
       x++; 
      } 
      i++; 
     } 
     x = temp_x + 1; 
     i = x; 
    } 
} 

我認爲這個問題是在if聲明。 你覺得呢?爲什麼會發生?我認爲我以積極的方式使用指向數組的指針。

謝謝!

+2

'我'會太大,並導致超出範圍的訪問,它調用*未定義的行爲*。 – MikeCAT

+2

使用-g編譯程序並在gdb下運行,這會告訴你它失敗的位置 – pm100

+0

嘗試使用[冒泡排序](https://en.wikipedia.org/wiki/Bubble_sort)方法(就像使用了[這裏](http://www.sanfoundry.com/c-program-sort-array-ascending-order/)按升序對數組進行排序) – iRove

回答

2

這個循環在你的程序

while (i >= 0) { 
     //... 
     i++; 
    } 

因爲i是unconditionly增加沒有意義。

程序可以看看下面的方式

#include <stdio.h> 

void bubble_sort(int a[], size_t n) 
{ 
    while (!(n < 2)) 
    { 
     size_t i = 0, last = 1; 

     while (++i < n) 
     { 
      if (a[i] < a[i-1]) 
      { 
       int tmp = a[i]; 
       a[i] = a[i-1]; 
       a[i-1] = tmp; 
       last = i; 
      } 
     } 

     n = last; 
    } 
} 

int main(void) 
{ 
    int a[] = { 6, 3, 6, 8, 4, 2, 5, 7 }; 
    const size_t N = sizeof(a)/sizeof(*a); 

    for (size_t i = 0; i < N; i++) printf("%d ", a[i]); 
    printf("\n"); 

    bubble_sort(a, N); 

    for (size_t i = 0; i < N; i++) printf("%d ", a[i]); 
    printf("\n"); 

    return 0; 
} 

程序輸出是

6 3 6 8 4 2 5 7 
2 3 4 5 6 6 7 8 

如果希望排序功能只有一個while循環,那麼你可以實現它通過以下方式

void bubble_sort(int a[], size_t n) 
{ 
    size_t i = 0; 

    while (++i < n) 
    { 
     if (a[i] < a[i-1]) 
     { 
      int tmp = a[i]; 
      a[i] = a[i-1]; 
      a[i-1] = tmp; 
      i = 0; 
     } 
    } 
} 
2

在你的內循環中,你增加了超出數組大小的i。您的算法應該要求您減少i,但我不確定這足以修復排序算法。

你應該首先嚐試實施冒泡排序與單while的循環,你比較相鄰的項目和退一步,只要你交換他們。