簡體   English   中英

我不明白為什么我的冒泡排序代碼無法正常工作

[英]I don't understand why my code for bubble sort does not work

for (int index = 0; index < size -1; index ++) {
    for (int index2 = 0; index2 < size - index; index2 ++) {
        if (index2 != (size - index) && array[index2] > array[index2 + 1] ) {
           store = array[index2 + 1];
          array[index2 + 1] = array[index2];
          array[index2] = store;
          printf ("%d",array[index2]);
          swap ++;
          comparison ++;
        }
    }
}

因此,這是使用氣泡排序算法交換和比較數組元素的代碼。 它適用於所有情況,但帶有兩個元素的數組除外。 我為此程序使用了C。 我用指針聲明了數組。

例如:

input: [2,0],
output: [0,1]

intput: [3.8],
output: [3,1]

一個錯誤。 根據您的代碼,第二個循環應為

for (int index2 = 0; index2 < size - index -1; index2 ++){ ...
for(i=1;i<n;++i)
for(j=0;j<(n-i);++j)
if(a[j]>a[j+1])
{
 temp=a[j];
 a[j]=a[j+1];
 a[j+1]=temp;
}

其中n =“數組大小” a [] =數組

輸入到輸出的第一個示例將0移到第一個位置,因為if語句為true array [index2]> array [index2 + 1]。 下一個示例不會傳遞參數的這一部分,從而使if參數返回一條錯誤的語句(因此它永遠不會將8移到3位置。接下來,我看到的問題是循環運行並要求輸入不屬於該部分的值示例Array [2] = 3,4;因此,當count = 2時具有Array [count + 1]時,您將獲取填充變量所需的下一組位。為什么您會得到垃圾輸出,希望對您有所幫助。我建議您在循環獲得不存在的值之前停止循環。

 #include "stdlib.h"   // includes _countof() returns the number of elements in the array
 Array[2] = 1,2;
 for(element = 0; _countof(array) != element && ...; element++) 
 {
 } 

_countof(array)返回2這一部分將替換第二個for循環的第一部分。 無論循環大小如何,它都會在循環超過數組限制之前停止循環。 將其他部分添加到該參數中,祝您好運,希望對您有所幫助。

這是氣泡排序算法的示例

#include <stdio.h>

int bubbleSort( int *array )
{


    for (int c = 0 ; c < ( n - 1 ); c++)
    {
        for (int d = 0 ; d < n - c - 1; d++)
        {
            if (array[d] > array[d+1]) /* For decreasing order use < */
            {
                int swap       = array[d];
                array[d]   = array[d+1];
                array[d+1] = swap;
            }
       }
   }

   return 0;
}

但是,如果要實現它,我將使用三個“異或”語句來實現交換,因為這樣就不需要交換變量了。 而且會快很多

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM