Question of C++

2008-04-28 4:36 am
An array with a list of numbers {89, 68, 5, 12} is to be sorted in ascending order using the selection sort algorithm. There should be 3 rounds of elements swapping before the list is sorted. Show the array contents after each round of swapping in sequence.

回答 (2)

2008-04-29 7:07 am
✔ 最佳答案
int number[4] = {89, 68, 5, 12};
int i, j;
int min, temp;

for (i = 0; i < 3; i )
{
min = i;
for (j = i 1; j < 4; j )
{
if (numbers[j] < numbers[min])
min = j;
}
temp = numbers[i];
numbers[i] = numbers[min];
numbers[min] = temp;
for (i = 0; i < 4; i ) cout << numbers[i];


note: < is the less than sign on your keyboard, yahoo cannot display it correctly.

2008-05-01 19:06:35 補充:
Firstly, I don't see how c27742003's answer allows only 3 rounds of swapping. It looks like it needs 4 rounds. Also, this doesn't seem like a selection sort method.

2008-05-01 19:06:44 補充:
Apart from this,
why the argument passing in the swap function is Swap(*int a, *int b)?
shouldn't it be Swap(int* a, int* b) if you means passing by pointers.

2008-05-01 19:06:52 補充:
And when passing the array element into the swap function, an address or the array element was passed in. Then, you call int Temp = a. I think Temp would then be the address of a. And then you assign *b as the address of a by calling *b = Temp?
maybe it should be:
int Temp = *a?

2008-05-01 19:07:00 補充:
Alternatively, it is easier to pass in by reference:
void swap(int &a, int &b)

Please correct me if im wrong.
2008-04-30 1:29 am
void Swap( *int a, *int b)
{
int Temp = a;
*a = b;
*b = Temp;
}

void main()
{
int dNum[4] = {89, 68, 5, 12};
for(int i=0; i<4 ; i )
{
for(int j= i 1; j<4; j )
{
if( dNum[i] > dNum[j] )
Swap( &dNum[i], &dNum[j] );
}
}
}

2008-04-29 17:35:49 補充:
如果你想方便D, 要加 / 減 SHOT 的總數
可以用 vector, 佢係個可以儲住無限大的array
而且儲任何DataType 都得!
特別之處係佢有埋一堆function
好似 size() 咁,會return 番個vector 的大細
咁你做 for loop 就唔駛理佢到底有幾大
只要 int i=0; i < vector.size(); i++
係咪好方便呢~~
用法係要 include
然後Create 要 vector name;

2008-04-29 17:37:17 補充:
include
vector dNum;

2008-04-29 17:39:36 補充:
Yahoo 食左我D 箭咀=.=
係 M字右邊果兩個箭咀
#include 開箭咀 vector 刪箭咀
vector開箭咀int刪箭咀 dNum;

2008-05-03 13:55:12 補充:
係喎=.=
打錯左好多野=.=
因為呢段野無經program build 過..
見到即場加係到=.=

不過你話用 void Swap(int &a, &b)
我又未試過丫~~我多數係用 *
* 左入去,可以作為function output
直接改左個數
好似 Dirext X 的 Function
好多都係用呢個方法
好處係可以一次過 return 多於一個變數


收錄日期: 2021-05-03 12:29:37
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20080427000051KK03186

檢視 Wayback Machine 備份