选择排序不正确排序

问题描述 投票:-1回答:1

数组无法正确排序,气泡排序和快速排序也可以正常工作。我已经检查了很多次,以发现任何错误,但是找不到一个。 (如果问题似乎不正确,请随意编辑)......................................... 。................................................... ................................................... ................................................... ...............................................

#include <iostream>
#include <ctime>
using namespace std;

const int MaxElements = 500;
int compCount = 0; // keeps track of comparisons of elements in array
int moveCount = 0; // keeps track of movement of elements in array

int main()
{
    // Declarations
    clock_t before; //time before sorting
    clock_t after; //time after sorting
    double result; //Total time 
    int n; //size of set
    int sample[MaxElements]; //array

    // Prompt the user for size of set
    cout << "Enter size of set: ";
    cin >> n;

    cout << "---------------Selection Sort-----------------\n";
    // Generate random values into the array
    generateSample(sample, n);

    cout << "Unsorted array: ";
    printElements(sample, n);

    before = clock();
    selectionSort(sample, n);
    after = clock();

    result = static_cast<double>(after - before) / CLOCKS_PER_SEC;

    cout << "\nSorted: ";
    printElements(sample, n);

    cout << endl << before << " " << after << "\n";
    cout << result << "\n";

    cout << "Movement: " << moveCount << endl;
    cout << "Comparison: " << compCount << endl;

}

// Swap algorithm
void swap(int* x, int* y)
{
    int temp = *x;
    *x = *y;
    *y = temp;
}

void selectionSort(int arr[], int n)
{
    int i,
        j,
        current;
    for (i = 0; i < n - 1; i++)
    {
        current = i;
        for (j = i + 1; j < n; j++)
        {
            compCount++;
            if (arr[j] < arr[current])
            {
                current = j;
            }
            if (current != i)
            {
                swap(arr[current], arr[i]);
                moveCount += 3;
            }
        }
    }
}
c++ sorting swap selection-sort
1个回答
2
投票

此if语句

        if (current != i)
        {
            swap(arr[current], arr[i]);
            moveCount += 3;
        }

必须放置在紧随其后的内部循环之外。

© www.soinside.com 2019 - 2024. All rights reserved.