Selection sort of C++ language (educoder)

Level 1: Second Statistics

mission details

The task of this level: write a c++ program, sort the sequence of integers from small to large, and select the second value (each number is only used once).

related information

Array declaration:

C++ supports array data structures, which can store a fixed-size sequential collection of elements of the same type. To declare an array in C++, you need to specify the type of elements and the number of elements. The general syntax is:

  1. type arrayName [ arraySize ];
  2. //元素类型 数组名称[元素个数]

for example:

double balance[10];

Description: An array is now balanceavailable that can hold numbers 10of type double.

Initialize the array:

In C++, you can initialize arrays individually, or with a single initializer statement. Initializing the array one by one looks like this:

  1. double balance[5];
  2. balance[0] = 1000.0;
  3. balance[1] = 2.0;
  4. balance[2] = 3.4;
  5. balance[3] = 7.0;
  6. balance[4] = 50.0;

An initialization statement looks like this:

double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};

If you omit the size of the array, the size of the array is the number of elements it was initialized with. for example:

double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};

Explanation: balanceThe length of the array is 5.

access array elements

Array elements can be accessed by indexing the array name. The index of the element is enclosed in square brackets, following the name of the array. Array indices 0start with . for example:

double salary = balance[9];

That is: assign the value of the index balancein the array 9to the variable salary.

selection sort

Selection sort ideas:

  • Traverse the column to be sorted from left to right to find the smallest element, and then exchange the position with the first element of the column to be sorted;
  • Then start from the second element and repeat the above operation until the last element.

Next, we int arr[] = {6,5,8,0,2,9}perform a round of operations on the array to move the maximum value to the first position of the array.

Code:

  1. int arr[] = {6,5,8,0,2,9};
  2. for (int i = 0; i < arr.length-1; i++) {
  3. if(arr[0] < arr[i+1]){
  4. int temp = arr[0];
  5. arr[0] = arr[i+1];
  6. arr[i+1] = temp;
  7. }
  8. }

One loop operation can find the maximum value in the array and move it to the first position of the array, so for an 6array with a length of , we only need to perform 5the above operations (length-1) times to sort the array in descending order.

Next we do a second loop, find the second largest value, and move it to the second position of the array. Because we have already calculated the maximum value, so this cycle, the maximum value does not need to participate in the comparison.

Code:

Output result:[9, 8, 5, 0, 2, 6]

It can be found that after two rounds of loops, we have found the two largest values ​​​​in the array and moved them to the first two digits of the array.

Now follow the steps above to sort the array.

programming requirements

Once, Bob wanted to find the second statistic in a sequence of integers. We select each number from the sequence and sort it from small to large (each number is used only once), and the value ranked second is the second statistical number. In other words, the second statistic is the smallest value in the series excluding the smallest number. Please help Bob solve this problem.

Input and output instructions:

  • The first line of input is an integer n(1 ≤ n ≤ 100), that is, the number of integers in the sequence The second line is a sequence of integersa1,a2,...,an(-100 ≤ ai ≤ 100)
  • If the sequence contains the second statistic, output this integer; otherwise, output NO.

Test example:

Test Input: 4 1 2 2 -4Expected Output:1

Test Input: 1 28Expected Output:NO


Let's start your mission, I wish you success!

code:

#include <iostream>
using namespace std;

int main()
{
    int n, m, l, temp, a[20];
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> m;
        a[i] = m;
    }
    if (n == 1)
    {
        cout << "NO";
    }
    else if (n >= 2)
    {
        for (int i = 0; i < n - 1; i++)
        {
            for (int j = 0; j < n - 1 - i; j++)
            {
                if (a[j] > a[j + 1])
                {
                    temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                }
            }
        }
        l = a[0];
        if (a[0] == a[n - 1])
        {
            cout << "NO";
        }
        else
        {
            for (int i = 1; i <= n; i++)
            {
                if (a[i] > l)
                {
                    cout << a[i];
                    break;
                }
            }
        }
    }
    return 0;
}

Level 2: Games Ranking

mission details

The task of this level: Write a c++ program to rank the results of the 100-meter competition in the sports meeting.

related information

Multidimensional Arrays

C++ supports multidimensional arrays. The general form of a multidimensional array declaration is as follows:

type name[size1][size2]...[sizeN];

The simplest form of a multidimensional array is a two-dimensional array. To declare a two-dimensional array is to declare an array of x rows and y columns, in the following form:

type arrayName [ x ][ y ];

for example:

#####Initializing Two-Dimensional Arrays Multidimensional arrays can be initialized by specifying values ​​for each row within parentheses. Below is an array with rows and 3columns4

  1. int a[3][4] = {
  2. {0, 1, 2, 3} , /* 初始化索引号为 0 的行 */
  3. {4, 5, 6, 7} , /* 初始化索引号为 1 的行 */
  4. {8, 9, 10, 11} /* 初始化索引号为 2 的行 */
  5. };

Inner nested parentheses are optional, the following initialization is equivalent to the above:

int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

access two-dimensional array

Elements in a two-dimensional array are accessed by using subscripts (that is, the array's row index and column index). for example:

int val = a[2][3];

Namely: Assign 3the 4value of the row-th element in the array to the variable val. ##### Selection Sort

See the previous level for selection sort details.

programming requirements

Knowing the results of the men's 100-meter race final in a certain sports meeting, it is required to write a program to sort by the results and output the sorting results, including the output of rankings, athlete numbers and results.

Tip: Use an array of M rows and 3 columns to store athlete numbers, results and rankings, sort the final results in descending order, and finally output the rankings according to the sorted positions. (M is the number of athletes)

Input and output instructions:

  • Enter athlete number and score
  • Output rankings, athlete numbers and results in sequence.

Test example:

Test Input: 1 9.06 2 9.55 3 9.50 4 9.56Expected Output:1 1 9.06 2 3 9.50 3 2 9.55 4 4 9.56


Let's start your mission, I wish you success!

 code:

#include <iostream>
#include <iomanip>
#define M 4
using namespace std;
int main()
{
    float A[M][3];
    for (int i = 0; i < M; i++)
    {
        for (int j = 1; j < 3; j++)
        {
            cin >> A[i][j];
        }
    }
    for (int k = 0; k < M; k++)
    {
        int min = k;
        for (int l = k + 1; l < M; l++)
        {
            if (A[min][2] > A[l][2])
            {
                float t = A[l][2];
                A[l][2] = A[min][2];
                A[min][2] = t;
                int t1 = A[l][1];
                A[l][1] = A[min][1];
                A[min][1] = t1;
            }
        }
    }
    int m = 1;
    int c = 1;
    A[0][0] = 1;
    while (m < M)
    {
        if (A[m][2] == A[m - 1][2])
        {
            A[m][0] = c;
            c--;
        }
        else
        {
            A[m][0] = c + 1;
        }
        m++;
        c++;
    }
    for (int a = 0; a < M; a++)
    {
        for (int b = 0; b < 2; b++)
        {
            cout << int(A[a][b]) << ' ';
        }
        cout << fixed << setprecision(2) << A[a][2] << ' ' << '\n';
    }
    return 0;
}

Level 3: Word Sorting

mission details

The task of this level: enter 8 words on the keyboard, and use sortLine()the function to sort these words.

related information

strcmp() function

Description: int strcmp(const char *str1, const char *str2)Compare str1the string pointed to with str2the string pointed to.

Parameters: str1The first string to compare. str2The second string to compare.

Return value: If str1less than str2, the return value is negative; if str1greater than str2, the return value is positive; if str1equal str2, the return value is0

for example:

  1. int main ()
  2. {
  3. char str1[15];
  4. char str2[15];
  5. int ret;
  6. strcpy(str1, "abcdef");
  7. strcpy(str2, "ABCDEF");
  8. ret = strcmp(str1, str2);
  9. if(ret < 0)
  10. {
  11. printf("str1 小于 str2");
  12. }
  13. else if(ret > 0)
  14. {
  15. printf("str2 小于 str1");
  16. }
  17. else
  18. {
  19. printf("str1 等于 str2");
  20. }
  21. return(0);
  22. }

Output result:str2 小于 str1

programming requirements

Complement the code between beignto endand complete sortLinethe function. Requirements are as follows:

  • 8Enter a word from the keyboard , use sortLineto sort these words (smaller first, larger last)
  • output the sorted words

Test instruction

Test Input: press presentation condor presume clap coke foul fosterExpected Output:clap coke condor foster foul presentation press presume


Let's start your mission, I wish you success!

code:

#include<iostream>
#include<string.h>
using namespace std;
void sortLint(char* a[8])
{
    char* temp;
    for (int i = 0; i < 7; i++)
    {
        for (int j = 0; j < 7; j++)
        {
            if (strcmp(a[j], a[j + 1]) > 0)
            {
                temp = a[j + 1];
                a[j + 1] = a[j];
                a[j] = temp;
            }
        }
    }
    for (int i = 0; i < 8; i++)
    {
        if (i != 7)
        {
            cout << a[i] << " ";
        }
        else
        {
            cout << a[i];
        }
    }
}
int main()
{
    char* a[8];
    for (int i = 0; i < 8; i++)
    {
        a[i] = new char[20];
        cin >> a[i];
    }
    sortLint(a);
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_62174595/article/details/127216988