想請問如何宣告一個陣列drade【n】存放n個值,之後輸入n個數值,依序為陣列元素,利用排序演算法由大而小排列?
1.輸入n個數值後,列出排序前的陣列元素內容。
2.由大而小排序完n個數值後,再列出排序後的陣列內容。
3.接下來輸入一個值,使用二分搜尋法來搜尋,找到後,列出陣列所在的索引值,找不到則輸出"找不到的訊息"。
4.需程式註解(方便我事後理解)
5.簡單來說->輸入數字資料->排序->二分搜尋。
題目有點文言,再麻煩各位了,感激不盡。
作業啊 ...... 自己寫才會進步!
都期末了,這個作業應該不算過份吧?
#include <iostream>
using std::cout;
using std::cin;
const int kMaxN = 100;
void printNumbers(int[], int);
int binarySearch(int[], int, int);
int main()
{
int n = 0, m = 0, tmp = 0;
int numbers[kMaxN];
// Input n.
cout << "N ? ";
cin >> n;
// Input numbers.
for(int i=0; i<n; ++i)
cin >> numbers[i];
// Sort numbers (bubble sort).
for(int i=0; i<n; ++i)
{
// Sort number[n-i-1].
for(int j=i+1; j<n; ++j)
{
if(numbers[i] < numbers[j])
{
tmp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = tmp;
}
}
}
// Print numbers.
cout << "Sorted :";
printNumbers(numbers, n);
cout << "\n";
// Search.
cout << "Search ? ";
cin >> m;
tmp = binarySearch(numbers, n, m);
if(tmp < 0)
cout << m << " not in array.\n";
else
cout << m << " is at index " << tmp << ".\n";
cout << "\n";
return 0;
}
void printNumbers(int array[], int n)
{
for(int i=0; i<n; ++i)
cout << " " << array[i];
cout << "\n";
}
int binarySearch(int array[], int arrayLength, int target)
{
int left = 0;
int right = arrayLength - 1;
int middle = (left + right) / 2;
// Binary search.
while(left <= right)
{
// Found.
if(array[middle] == target)
return middle;
// Search in right part.
else if(array[middle] > target)
left = middle + 1;
// Search in left part.
else
right = middle - 1;
middle = (left + right) / 2;
}
// Not found.
return -1;
}
本月已經看到不只兩個求作業的
應該有個四五個吧!