簡體   English   中英

bubbleSort 僅排序第一個元素 C++

[英]bubbleSort only sorts first element C++

我已經嘗試以我能想到的各種方式實現氣泡排序算法,但它仍然只對第一個數字進行排序。 我不明白為什么會這樣。 任何見解都會很有幫助! 我試過***請注意我必須對數組進行排序(所以不能在實現中使用向量)。

冒泡排序.h

#ifndef BUBBLE_SORT_
#define BUBBLE_SORT_

#include <cstddef>
#include <iostream>
#include <array>

using std::size_t;

// void displayBag(ArrayBag &bag);
void bubbleSort(int arr[], size_t n);

#endif

冒泡排序.cpp

#include "bubbleSort.h"

#include <iostream>
#include <cstddef>
#include <array>
#include <vector>

using std::cout; using std::endl; using std::vector; using std::size_t;

/****************************************************************************/ 
/* Function:    bubbleSort
/* Inputs:      n = num of elements in arr
                arr = arr to be sorted
/* Outputs:     outputs sorted arr to console 
/* Purpose:     This function sorts arr in ascending order 
/****************************************************************************/ 
void bubbleSort(int arr[], size_t n)
{
    int i = 0;
    int j = 0;
    for(i; i < n; i++)
    {   
        for(j; j < (n-1); j++)
        {
            if (arr[j] > arr[j+1])
            {
                {
                    int temp = arr[j+1];
                    arr[j+1] = arr[j];
                    arr[j] = temp;
                }
            }
        }
    }
}

主文件

#include "bubbleSort.h"
#include "bubbleSort.cpp"

#include <cstddef>
#include <iostream>
#include <array>

using std::cout; using std::endl;

int main() 
{ 
    int arr[] = {64, 34, 25, 12, 22, 11, 90}; 
    size_t n = sizeof (arr) / sizeof (int); 
    cout << "The array has " << n << " elements." << endl;
    bubbleSort(arr, n);
    printf("Sorted array: \n");
    for (int i=0; i < n; i++) 
    {
        cout << arr[i] << " ";
    }
    return 0; 
} 
  1. 在第一個外循環之后, j的值已經是n-1 ,所以內循環不會運行。

  2. 在每個外循環之后,最后i個元素被排序,所以它應該是for (j = 0; j < (ni-1); j++)

為兩件事更新你的循環:

  • 為每次運行初始化內部循環
  • 要優化循環,請執行 (n - i - 1)

暫無
暫無

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

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