2017-04-11 46 views
0

我目前正在用C語言創建此程序,其目的是使用Bubble排序算法對包含多個元素的靜態數組進行排序。冒泡排序可能不是一種快速有效的算法,但我將其用於教育目的。確定數組是否完全排序

這個節目幾乎是我的作品想要的方式,它的排序,但我有以下問題:

  • 我do-while循環不斷重複,即使數組本身完全排序。現在它正在循環,我希望它在整個數組正確排序時停止。

如何確定整個數組是否已排序,然後在完全排序時停止迭代?

這裏是我的代碼:

#include <stdio.h> 

int main() 
{ 
    int list[] = {5,1,5,4,3,2,1}; 
    int length = sizeof(list)/sizeof(int); 

    printf("Unsorted array\n"); 
    printf("-----------------------------\n\n"); 

    for (int i = 0; i < length; i++) 
    { 
     if (i < length - 1) 
      printf("%d, ", list[i]); 
     else 
      printf("%d", list[i]); 
    } 

    do 
    { 
     for (int i = 0; i < length - 1; i++) 
     { 

      if (list[i] > list[i + 1]) 
      { 
       printf("\n* Moving %d and %d", list[i], list[i + 1]); 
       int temp = list[i + 1]; 
       list[i + 1] = list[i]; 
       list[i] = temp; 
      } 

      else 
      { 
       getchar(); 
      } 

      getchar(); 
     } 
     printf("-----------------------------\n"); 

     for (int i = 0; i < length; i++) 
     { 
      if (i < length - 1) 
       printf("%d, ", list[i]); 
      else 
       printf("%d", list[i]); 
     } 

    } while (1); 

    printf("Goodbye!\n"); 
    getchar(); 
    return 0; 
} 
+0

https://en.wikipedia.org/wiki/Bubble_sort說明如何知道何時終止。 –

回答

0

爲什麼你認爲你的泡沫排序需要永遠持續下去?

在inner for循環的一次迭代結束時,最大的元素將冒泡(因此名稱)到數組的末尾。所以你會知道它是在正確的地方。

這意味着在下一次迭代時,只需對第一個元素進行冒泡排序。在第三次迭代中,您只需要對第一個length - 3元素進行排序等等,直到您發現自己排序第一個元素爲止。那時,你知道要停下來。

因此,您的do ... while循環可以是for循環。

for (int sortLength = 1 ; sortLength < length ; ++ sortLength) // replaces your do while loop 
{ 
    for (int i = 0 ; i < length - sortLength ; ++i) 
    { 
     // Element swap stuff same as before 
    } 

    // print loop same as before 
} 
1

你寫:

do [...] while (1) 

這意味着while循環將永遠不會結束,1將被評估爲true,除非有一個break或goto語句在循環中(感謝Flikk)。

+0

除非循環中出現中斷或跳轉 – Flikk

+0

@Flikk,但沒有。 – JeremyP

+0

我知道這種情況,但這只是一個臨時解決方案。 – SteelInTheWheel

2

您可以使用flag變量來檢查以前迭代中是否存在某些交換。如果沒有,數組已經排序並獲得循環。

int flag = 0; 
for (int i = 0; i < length - 1; i++) 
{ 

    if (list[i] > list[i + 1]) 
    { 
     printf("\n* Moving %d and %d", list[i], list[i + 1]); 
     int temp = list[i + 1]; 
     list[i + 1] = list[i]; 
     list[i] = temp; 
     flag = 1; 
    } 
    else 
    { 
     getchar(); 
    } 

    getchar(); 
} 

if (!flag) break; 
相關問題