简体   繁体   English

对整数数组应用选择排序

[英]Applying selection sort on an array of integers

int arr[] = {7,4,10,8,3,1};
int size = sizeof(arr) / sizeof(arr[0]);

for(int i = 0; i<size-1; i++){
    
    int temp = arr[i];
    
    for(int j = i+1; j < size; j++){
        
        if(arr[j] < temp){
            temp = arr[j];
        }
        
    }
    
    swap(temp, arr[i]);
}

I am trying to apply the selection sort algorithm on the given array, but the output I am getting is only [1,1,1,1,1,1] , I am finding the minimum element through the inner loop, Ican't figure out what is going wrong?我正在尝试对给定数组应用选择排序算法,但我得到的 output 只是[1,1,1,1,1,1] ,我通过内循环找到最小元素,我不能弄清楚出了什么问题?

Slightly modified your code;稍微修改了你的代码;

You need to pass reference(address) to both elements to take place of swapping contents您需要将reference(address)传递给两个元素以代替交换内容

int arr[] = { 7, 1, 10, 8, 3, 11, 0, 12, 5, 8 };
int size = sizeof(arr) / sizeof(arr[0]);

for(int i = 0; i < size; i++)
{
   auto temp = std::min_element( arr + i, arr + size );

   std::swap( arr[i], *temp );      
}

You have to add algorithm header to use std::min_element您必须添加algorithm header 才能使用std::min_element

int arr[] = {7,4,10,8,3,1};
int size = sizeof(arr) / sizeof(arr[0]);

for(int i = 0; i<size-1; i++){
    
    int temp = arr[i];
    int pos = i;
    
    for(int j = i+1; j < size; j++){
        
        if(arr[j] < temp){
            temp = arr[j];
            pos = j;
        }
        
    }
    
    if(pos != i)
        std::swap(arr[pos], arr[i]);
}

This should work.这应该工作。

It is suggested not to use using namespace std;建议不要使用using namespace std; . . There is a plethora of reasons why you should not ;不应该这样做的原因有很多; that I will not mention.我不会提到。

By the way I tried to keep some of your variables the same but to be honest, I didn't.顺便说一句,我试图让你的一些变量保持不变,但老实说,我没有。 It is better to create variable names that explain what the code is doing.最好创建变量名来解释代码的作用。 It makes your code a lot more legible and readable.它使您的代码更加清晰易读。

So opt out of one letter variables.所以选择退出一个字母变量。 It is fine in for loops, however this is a special case.for循环中没问题,但这是一种特殊情况。

Now, here is another alternative suggested by @user4581301 & @Swift -Friday Pie.现在,这是@user4581301 和@Swift -Friday Pie 建议的另一种选择。 This method is using std::size using c++17 .此方法使用std::size使用c++17

For example:例如:

#include <iostream>
#include <utility> // to use the swap() function.
#include <iterator> // to use std::size() function.


int main()
{
    int arr[] = { 7,4,10,8,3,1 };
    // This --> int size = sizeof(arr) / sizeof(arr[0]); is archaic.

    const int length = static_cast<int>(std::size(arr)); // Call this something other than "size"; you can run into issues. 
   // We use static_cast<int>  as a implicit conversion, and the obvious std::size(arr)).
   
    

   // Going through the elements

    for (int StartOfIndex = 0; StartOfIndex < length - 1; ++StartOfIndex)
    {
        // smallest is the index of the smallest element we’ve encountered this iteration

        int smallest = StartOfIndex;

        // Looking for a smaller element..
        for (int current = StartOfIndex + 1; current < length; ++current)
        {
            // if we found an element smaller than our last; take note.
            if (arr[current] < arr[smallest])

                smallest = current;
        }

        // swap StartOfIndex with smallest.
        std::swap(arr[StartOfIndex], arr[smallest]);
    }

    //Prints array.
    for (int index = 0; index < length; ++index)
        std::cout << arr[index] << " ";

    std::cout << "\n";

    return 0;
}

Output: 1 3 4 7 8 10 Output: 1 3 4 7 8 10

void swap(int *xp, int *yp)  
{  
    int temp = *xp;  
    *xp = *yp;  
    *yp = temp;  
}  
  
void selectionSort(int arr[], int n)  
{  
    int i, j, min_idx;  
  
    // One by one move boundary of unsorted subarray  
    for (i = 0; i < n-1; i++)  
    {  
        // Find the minimum element in unsorted array  
        min_idx = i;  
        for (j = i+1; j < n; j++)  
        if (arr[j] < arr[min_idx])  
            min_idx = j;  
  
        // Swap the found minimum element with the first element  
        swap(&arr[min_idx], &arr[i]);  
    }  
}  


selectionSort(arr,size);

This should work.这应该工作。

The first mistake you made in writing for loop's condition, don't use swap(temp, array[i]);你在编写 for 循环条件时犯的第一个错误,不要使用swap(temp, array[i]); yet try to get the basics first.但首先尝试获得基础知识。

#include <iostream>

using namespace std;

int findsmall(int arr[], int i, int size){
    int s, pos, j;
    s = arr[i];
    pos = i;
    for(j = i+1; j < size; j++){
        if(arr[j] < s){
            s = arr[j];
            pos = j;
        }
    }
    return pos;
}

int main() {
    
    int arr[] = {7,4,10,8,3,1};
    int size = sizeof(arr) / sizeof(arr[0]);
    int smallnum;
    int temp;
    int count = 0;
    
    cout << "Original array: ";
    
    for(int i = 0; i < size; i++){
        if(i < size - 1){
        cout << arr[i] << ", ";}
        else{
            cout << arr[i];
        }
    }
    
    cout << endl;
    
    for(int i = 0; i < size; i++){
        smallnum = findsmall(arr,i, size);
        temp = arr[i];
        arr[i] = arr[smallnum];
        arr[smallnum] = temp;
        count++;
    }
    
    
    
    cout << "Sorted array: ";
    
    for(int i = 0; i < size; i++){
        if(i < size - 1){
        cout << arr[i] << ", ";}
        else{
            cout << arr[i];
        }
    }
    
    cout << endl;
    
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM