【问题标题】:C++ insertion sorting elementsC++ 插入排序元素
【发布时间】:2015-06-02 17:38:54
【问题描述】:

元素在功能中而不是主程序中的其他方式?

void insertionSort(int array[], int number)
{

    int j, temp;
    for (int i = 1; i<number; i++)
    {
        j = i;
        while (j>0 && array[j - 1]>array[j])
        {
            temp = array[j];
            array[j] = array[j - 1];
            array[j - 1] = temp;

            j--;
        }
    }

}



int main()
{

    int number = 8;

    int array[] = { 2, 7, 5, 6, 4, 8, 1, 3 };

    insertionSort(array, 8);

    for (int i = 0; i<number; i++)
        cout << array[i] << " ";
    cout << endl;

    system("PAUSE");

    return 0;
}

【问题讨论】:

  • 请解释Other way for elements to be in function instead of main program?。你想让数组在排序函数中而不是在主函数中吗?
  • 是的,如果可能的话
  • ... 您可以从insertionSort 过程中删除“array”和“number”参数,并像在main 中那样将它们作为局部变量引入过程本身。我不知道这样的程序有什么意义

标签: c++ sorting insertion-sort


【解决方案1】:

虽然要排序的数据可以移到排序函数中,但这样做会创建一个几乎没有用的函数——因为它只对一组数据进行排序,它相当于@987654321 @

您的插入排序也有点乱。插入排序的伪代码通常如下所示:

for i in 1 to size do 
    temp = array[i]
    for j in i downto 0 and array[j-1] > temp do
        array[j] = array[j-1]
    array[j] = temp

【讨论】:

    【解决方案2】:

    我建议你不要这样做。一个函数应该是一段可重用的代码。如果将数组硬编码到函数中,则该函数只能对函数中的数组进行排序,并且您必须编辑函数中的数组才能对不同的内容进行排序。通过将数组传递给函数,您现在可以将任何数组传递给函数,并且它将被排序。您甚至可以在同一个程序中使用不同的数组多次调用该函数,它们将被排序。

    我还要提到,如果您将数组移动到排序函数中,那么它将不在main() 中,并且您将无法像现在一样打印出main() 中的数组.

    【讨论】:

    • 好的,非常感谢。我是初学者,我犯了很多错误,我有很多事情要弄清楚。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 2014-03-15
    • 1970-01-01
    • 2013-02-09
    • 2016-04-13
    相关资源
    最近更新 更多