2014-09-21 60 views
0

我为整数创建了一个数组冒泡排序函数,它与正整数完美协作,但是当使用负整数时会崩溃。初始显示功能可以工作,但只会冻结。我试过一个signed int数组无效。C++ Bubble Sort Negative Numbers

我已经看了所有,但无法找到任何其他人与这个确切的问题。

int defaultArray[6] = { 12, -5, 21, -1, 15, 17 }; 
    int numElements = 6; 

    int lastSwap; 
    int searchEnd = numElements - 1; 
    bool sorted = false; 

    while (!sorted) 
    { 
     for (int i = 0; i < searchEnd; ++i) 
     { 
      // If the number in position i is larger than the number in the 
      // position i + 1 then swap them 

      if (defaultArray[i] > defaultArray[i + 1]) { 
       int temp = defaultArray[i]; 
       defaultArray[i] = defaultArray[i + 1]; 
       defaultArray[i + 1] = temp; 
       lastSwap = i + 1; 
      } 
     } 

     // If the lastSwap is at position one we can conclude that the array is 
     // sorted so if lastSwap isn't 1 move searchEnd and continue 
     if (lastSwap != 1) 
     { 
      // Conclude that from lastSwap to the end of the array is sorted 
      // searchEnd begins one position to the left of lastSwap 
      searchEnd = lastSwap - 1; 
     } 
     else { 
      sorted = true; 
     } 
+1

你有点忘了描述问题。你只是说它“停止工作”。但是,这是什么意思?它会崩溃吗?它会永久循环吗?它会产生不正确的结果吗? – 2014-09-21 00:33:24

+0

这里没有你所有的代码。你最初在哪里设置'lastSwap',你在哪里设置你的(外部)循环? – 2014-09-21 00:44:03

+0

有一件事,如果你的数组开始排序,lastSwap仍然未定义,searchEnd也是如此。 – dhavenith 2014-09-21 00:44:45

回答

1

您正试图优化您的算法降低searchEnd,我认为存在问题。我建议你保持searchEnd一样。要确定数组是否已排序,请将sorted设置为true,并将while循环的开始处设置为false,如果发生交换,则将其更改为false。例如:

while (!sorted) { 
    sorted = true; 
    for (int i = 0; i < searchEnd; ++i) { 
     if (defaultArray[i] > defaultArray[i + 1]) { 
      // swap 
      sorted = false; 
     } 
    } 
} 
+0

即使我留在优化工作。我仍然不明白为什么它崩溃,但谢谢。 – 2014-09-21 00:47:41