2014-09-21 110 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. 
發現功能