0

C++題目求解(急!!)

snbb 2021-06-23 11:58:491097 瀏覽

1.輸入n個數值後，列出排序前的陣列元素內容。
2.由大而小排序完n個數值後，再列出排序後的陣列內容。
3.接下來輸入一個值，使用二分搜尋法來搜尋，找到後，列出陣列所在的索引值，找不到則輸出"找不到的訊息"。
4.需程式註解(方便我事後理解)
5.簡單來說->輸入數字資料->排序->二分搜尋。

4 個回答

0

iT邦大神 1 級 ‧ 2021-06-23 12:34:01

0

iT邦大師 1 級 ‧ 2021-06-23 13:28:45

0
aaronhunter
iT邦新手 4 級 ‧ 2021-06-24 09:22:01

0
haward79
iT邦新手 4 級 ‧ 2021-06-24 13:55:08

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