简体   繁体   English

C++ arrays中的排序数字

[英]C++ Sorting numbers in arrays

I am trying to get this out put:我正在努力解决这个问题:

  • 1 10 1 10
  • 2 9 2 9
  • 3 8 3 8
  • 4 7 4 7
  • 5 6 5 6

How do I do that?我怎么做?

My code:我的代码:

 #include <iostream>
    #include <cmath>
    
    using namespace std;
    
    int main()
    {
        const int n=10;
        int Tab[n]={1,2,3,4,5,6,7,8,9,10};
    
    
        for(int i=0; i<5; i++)
            for(int j=5; j>=0; j--)
                cout << Tab[i] << " " << Tab[j] << endl;
    
    
        return 0;
    }

How do I do that?我怎么做?

You do not need 2 loops, you just use one loop and calculate second index:您不需要 2 个循环,只需使用一个循环并计算第二个索引:

    for(int i=0; i<n/2; i++) 
        cout << Tab[i] << " " << Tab[n-i-1] << endl;

Live example活生生的例子

PS in this form for array with odd number of elements it will skip middle one.对于具有奇数个元素的数组,这种形式的 PS 将跳过中间一个。 If you want it to be printed twice instead, change loop condition to this:如果您希望它被打印两次,请将循环条件更改为:

    for(int i=0; i<(n+1)/2; i++) 

for even elements it will work as before.对于偶数元素,它会像以前一样工作。

There are multiple issues with your code.您的代码存在多个问题。

  1. You need to iterate all the elements of the array.您需要迭代数组的所有元素。 So for loop condition should be i<(length of array).所以for循环条件应该是i<(数组长度)。

  2. There are multiple sorting algorithms to sort an array and in each of these algos you need to compare the element you are processing with other elements to decide its location in final array.有多种排序算法可以对数组进行排序,在每种算法中,您都需要将正在处理的元素与其他元素进行比较,以确定其在最终数组中的位置。

pseudo code should look like伪代码应该看起来像

first for loop
    second for loop 
      if element ith  > element jth   //assuming you wanted to sort in ascending format
         swap(element i and j)

I am not sharing full code since it seems like a homework problem and I suggest you should try to solve yourself.我没有分享完整的代码,因为这似乎是一个家庭作业问题,我建议你应该尝试自己解决。

If you see any other issue.如果您看到任何其他问题。 Please update your question.请更新您的问题。

If you want to sort your array, you can use std::sort function.如果要对数组进行排序,可以使用 std::sort function。 This function works on array or vector.这个 function 适用于数组或向量。 Yours is array.你的是数组。 Two arguments are required: the beginning of the array and the length n up to which you want the array to be sorted.需要两个 arguments:数组的开头和希望数组排序的长度 n。 Example例子

#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    sort(arr, arr + n);
 
    cout << "\nArray after sorting ";

    for (int i = 0; i < n; ++i)
        cout << arr[i] << " ";
 
    return 0;
}

This will sort in ascending order.这将按升序排序。 You can add one more argument to sort in descending order:您可以再添加一个参数以降序排序:

sort(arr, arr + n, greater());排序(arr,arr + n,更大());

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

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