2017-03-02 44 views
0

我有一個任務,我一直堅持,並經過相當多的研究後無法弄清楚。嘗試使用在數組中找到最小值的函數按升序對數組進行排序?

我需要使用返回數組中最小值的函數對大小爲20的數組進行排序。

這是我的函數,返回數組中的最小值。

int problem5(int *arr, int size, int &m, int &n){//Definition Problem 5 
    int smallest = 101; 
    int smallestindex; 
    for (int i=0; i < size; ++i){ 
     if (arr[i] < smallest){ 
      smallest = arr[i]; 
      smallestindex = i; 
     } 
    } 
    m=smallest; 
    n=smallestindex; 
    cout<<"Smallest value is "<<m<<endl; 
    cout<<"It's index is "<<n<<endl; 
    return n; 
}` 

這裏是我的功能,我想切換與最小值的索引數組中的第一個值的索引,然後在陣列不包括在第一值(最小值)新陣列。這裏是代碼:

void problem8(int *x, int size){ 
    int m = 101; 
    int n = 101; 
    int tmpsize = size; 
    problem4(x,20); 
    for(int i =0; i<size; i++){ 
     swap(x[i],x[problem5(&x[i],tmpsize, m, n)]); 
     tmpsize = tmpsize - 1; 
    }  
}` 

對於前幾個循環,它不會更改數組,但會正確識別最小值。預先感謝您的幫助。

+3

你應該嘗試使用[調試器](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。 – Fureeish

+0

簡單。使用'std :: sort'對數組進行排序,然後第一個槽中的值將是最小的。 –

+0

'problem4()'的定義是什麼? –

回答

0
swap(x[i], x[problem5(&x[i], tmpsize, m, n)]); 

應該

problem5(&x[i], tmpsize, m, n); 
swap(x[i], x[n]); 

你目前可能有越界訪問。

我建議還可以重命名變量nmproblem8成類似smallIndexsmallestValue。導致到類似:

int find_min(const int* arr, int size, int& value, int& index) 
{ 
    int smallest = 101; 
    int smallestindex; 
    for (int i = 0; i < size; ++i) { 
     if (arr[i] < smallest) { 
      smallest = arr[i]; 
      smallestindex = i; 
     } 
    } 
    value = smallest; 
    index = smallestindex; 
    return n; 
} 

int problem5(int* arr, int size, int& m, int& n) 
{ 
    int res = find_min(arr, size, m, n) 
    std::cout << "Smallest value is "<< m << std::endl; 
    std::cout << "It's index is " << n << std::endl; 
    return res; 
} 

void selection_sort(int* x, int size) 
{ 
    int value = 101; 
    int index = 101; 
    int tmpsize = size; 

    for(int i = 0; i<size; i++) { 
     problem5(&x[i], tmpsize, value, index); 
     swap(x[i], x[index]); 
     tmpsize = tmpsize - 1; 
    } 
} 

void problem8(int* x, int size){ 
    problem4(x, 20); // better name ? 
    selection_sort(x, size); 
} 
+0

感謝您對名稱的輸入。不幸的是,由於我的教授的指示,我們必須使用problemX()作爲函數名稱,但我確實更改了實際變量。我閱讀了您的更改,並且點擊了一下,我認爲它可以很好地工作,但它仍然返回相同的結果。謝謝你的幫助,但我很欣賞這些指針。 – gseelig

+0

我保留'problemX'這個名字,因爲我相信它是必需的,但是你可以用很好的名字創建子函數。 – Jarod42