C++ 数组排序函数-C++;

C++ 数组排序函数-C++;,c++,arrays,C++,Arrays,目的是创建一个随机数数组,并按升序排序 数组已创建,但排序不起作用(数字以随机顺序打印) 我是否错误地应用了按引用排序 #include <iostream> #include <chrono> #include <ctime> using namespace std; void mySort(long x[]) { long min(0), temp(0), minPosition(0), i(0), j(0); min = x[0]; for (j

目的是创建一个随机数数组,并按升序排序 数组已创建,但排序不起作用(数字以随机顺序打印) 我是否错误地应用了按引用排序

#include <iostream>
#include <chrono>
#include <ctime>
using namespace std;

void mySort(long x[])
{
long min(0), temp(0), minPosition(0), i(0), j(0);
min = x[0];


for (j = 0; j < 10; j++)
{


    for (i = j; i < 10; i++)
    {
        if (x[i] < min)
        {
            min  = x[i];
            minPosition = i;
        }
    }


    temp = x[minPosition];
    x[minPosition] = x[j];
    x[j] = temp;

}


}

int main()
{

long *myArray = new long[10];
int i(0);

srand((unsigned int)time(NULL));
for (i = 0; i < 10; i++)
{
    myArray[i] = rand()%11;
}

mySort(myArray);
for (i = 0; i < 10; i++)
{
    cout<<'['<<myArray[i]<<']'<<endl;
}
return 0;

}
#包括
#包括
#包括
使用名称空间std;
void mySort(长x[])
{
长min(0)、温度(0)、最小位置(0)、i(0)、j(0);
min=x[0];
对于(j=0;j<10;j++)
{
对于(i=j;i<10;i++)
{
如果(x[i]cout最突出的一点是,每次外循环启动时,您都需要重置
min
minPosition
。目前,从第二次迭代开始,情况将变得非常糟糕


另外,请注意,这(选择排序)是一种对列表进行排序的低效方法。它在
O(n^2)
时间内运行,而不是
O(n log n)
,这是好的排序算法(快速排序、堆排序、合并排序)所做的工作。

如果您不知道如何排序,您可以使用sort()函数

// sort() Example using arrays.
#include <iostream>
#include <algorithm>

using namespace std;

const int SIZE = 7;

int main()
{
    int intArray[SIZE] = {5, 3, 32, -1, 1, 104, 53};

    //Now we call the sort function
    sort(intArray, intArray + SIZE);

    cout << "Sorted Array looks like this." << endl;
    for (size_t i = 0; i != SIZE; ++i)
        cout << intArray[i] << " ";

    return 0;
}
Parameter 1 myvector.begin() ~ The first parameter is where you will be putting a iterator(Pointer) to the first element in the range that you want to sort. The sort will include the element that the iterator points to.

Parameter 2 myvector.end() ~ The second parameter is almost like the first but instead of putting a iterator to the first element to sort you will be putting a iterator to the last element. One very important difference is that the search won’t include the element that this iterator points to. It is [First,Last) meaning it includes the first parameter in the sort but it doesn’t include the second parameter in the sort.

Parameter 3 myCompFunction() Optional ~ The third parameter is used to define how you do the search. For example if you have a struct that has 3 different variables in it.