给定一个整数数组 A(20).将 Min 元素放在数组的开头

Given an array of integers A(20). Put Min element in the beginning of the array

本文关键字:数组 元素 Min 开头 一个 整数      更新时间:2023-10-16

任务是:给定一个包含 20 个整数 A(20) 的数组。在其中找到最小正整数并将其放在数组的开头。显示初始数组和更改的数组。

我的代码是(现在可以工作了):

#include <iostream>
using namespace std;
int main(){
    int arrayA[20]={6,7,8,9,10,11,12,1,2,3,4,5,13,14,15,16,17,18,19,20};
    int min=arrayA[0];
    int i, minplace;
    //array's showing in the screen
    cout<<"Array A: n";
    for(i=0; i<20; i++)
    cout<<arrayA[i]<<" ";
    cout<<endl;
    //min value of array's element
    for(int i=0; i<20; i++)
        if (arrayA[i]<min)
        {
            min=arrayA[i];
            minplace=i;
        }
    cout<<"Min element's value of the array A: "<<min<<endl;
    //array 2
    int arrayB[21]={min,6,7,8,9,10,11,12,1,2,3,4,5,13,14,15,16,17,18,19,20};
    //array's showing in the screen
    cout<<"Array B: n";
    for(i=0; i<21; i++)
    cout<<arrayB[i]<<" ";
    cout<<endl;
    int k=minplace+1;
    int n=21;
    for (int i=minplace+1; i<n; i++)
    arrayB[i]=arrayB[i+1];
    n=n-1;
    cout<<"Array with deleted element: "<<endl;
    for (int i=0; i<n; i++)
    cout<<arrayB[i]<<" ";
    return 0;
 }

此代码现在有效。

这是一个非常模糊的问题,但我确实注意到,当你使用变量X时,你永远不会把它分配给任何东西。

这是一种更好的方法,它只使用单个数组,并且更精确和干净。希望这可能有助于某人学习。

#include <iostream> 
using namespace std;
int main(){
    int arrSize = 20;
    int myArray[20] = {6,7,8,9,10,11,12,1,2,3,4,5,13,14,15,16,17,18,19,20};
    cout<<"Initial Array:t";
    /* loop for printing the initial array */
    for(int i = 0; i<arrSize; i++)
    cout<< myArray[i]<< " ";
     /* assuming the first element of the array is the minimum */
    int minIndex = 0;
    int min = myArray[minIndex];
    /* loop for finding the minimum value */
    for(int i = 0; i<arrSize; i++){
      /* condition for checking if the current element is the minimum */
      if(myArray[i]<min){
        min = myArray[i];
        minIndex = i;
      }
    }
    /* swaping the first element of the array with the minimum element */
    myArray[minIndex] = myArray[0];
    myArray[0] = min;
    cout<<"nFinal Array:t";
    /* loop for printing the final array */
    for(int i = 0; i<arrSize; i++)
    cout<< myArray[i] << " ";   
return 0;    
}