2014-09-21 79 views
-2

意图是创建一个随机数组,并按升序排序 数组已创建,但排序不起作用(数字以随机顺序打印) 我有错误地应用排序?脱颖而出数组排序功能 - C++

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

} 

回答

1

一件事是,你需要重新设置你的每一个外循环揭开序幕时间minminPosition。目前,从第二次迭代开始,事情就会发生严重错误。

此外,请注意,此(选择排序)是排序列表的相当低效的方式。它运行在O(n^2)时间,而不是O(n log n),这是什么好的排序算法(Quicksort,Heapsort,Mergesort)。

0

那么,如果你不知道如何排序...你可以使用排序()作为

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

在〜#include <algorithm>

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. 
发现功能