无论如何,要使这种排序算法更有效/更短C ++

时间:2015-01-06 23:34:56

标签: c++ sorting if-statement for-loop while-loop

// 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语句

2 个答案:

答案 0 :(得分:2)

您可以使用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;
}

答案 1 :(得分:1)

这样的事情:

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;
  }
}