无论如何让这个排序算法更 efficient/shorter C++

Anyway to make this sorting algorithm more efficient/shorter C++

// Number Sorting Algorithm - Trey Taylor 2014
#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;
    int main() {
        int numbersort [] = {200, 85, 63, 4}
        cout << "The numbers scrambled are: ";
        cout << numbersort[0] << ", ";
        cout << numbersort[1] << ", ";
        cout << numbersort[2] << ", ";
        cout << numbersort[3] << ", " << endl;
        firstlast:
        if (numbersort[0] > numbersort[1]) {
            int temp = 0;
            temp = numbersort[0];
            numbersort[0] = numbersort[1];
            numbersort[1] = temp;
        }
            if (numbersort[1] > numbersort[2]) {
                int temp = 0;
                temp = numbersort[1];
                numbersort[1] = numbersort[2];
                numbersort[2] = temp;
            }
                if (numbersort[2] > numbersort[3]) {
                    int temp = 0;
                    temp = numbersort[2];
                    numbersort[2] = numbersort [3];
                    numbersort[3] = temp;
                }
                        while (numbersort[0] > numbersort[1]) {
                        goto firstlast;
                }
        cout << "The numbers unscrambled are: ";
        cout << numbersort[0] << ", ";
        cout << numbersort[1] << ", ";
        cout << numbersort[2] << ", ";
        cout << numbersort[3] << ", ";
}

有谁知道是否有办法使用 for 或 while 循环将数组中的数字从左到右重新排列为升序,而不是仅使用 3 个 if 语句

像这样:

i = 0;
while (i < (sizeof(numbersort)/sizeof(numbersort[0])) - 1)
{
  if (numbersort[i] >= numbersort[i + 1])
  {
    std::swap(numbersort[i], numbersort[i + 1]);
    i = 0;
  }
  else
  {
    ++i;
  }
}

您可以使用 std::sort 或冒泡排序算法 (link how it works)。算法检查是循环中的当前数字比下一个大。如果是更改数组中的那些数字。最后你在数组的末尾得到最大的数字,在数组的开头得到最小的数字。

int main()
{
    int numbersort[] = { 200, 85, 63, 4 };
    int temp = 0;
    // This loop sorts all numbers in the array
    for (int z = 0; z < 4; ++z)
    {
        // This loop sorts only one number to the end
        for (int i = 0; i < 3; ++i)
        {
            if (numbersort[i] > numbersort[i + 1])
            {
                temp = numbersort[i];
                numbersort[i] = numbersort[i + 1];
                numbersort[i + 1] = temp;
            }
        }
    }

    cout << "Sorted numbers" << endl;
    for (int i = 0; i < 4; ++i)
    {
        cout << numbersort[i] << endl;
    }

    system("pause");
    return 0;
}