撰寫了一個小程式,隨機生成100個100以內的陣列,并對這個陣列進行從小到大的排序,但程式跑下來一直是第一個數是最大的,從第二數開始才是正確的,這是為什么呢?
代碼如下:
#include "stdafx.h"
#include "iostream"
#include "time.h"
#include "cstdlib"
const int num = 100;
using namespace std;
void show_ar(int * a);
int main()
{
int ar[num];
srand(time(0));
for (int i = 0; i < num; i++)
ar[i] = rand() % 100;
show_ar(ar);
//rearrangement arrary.
cout << "After rearrangement:\n";
for (int i = 0; i < num; i++)
{
int temp = ar[i];
int index = 0;
for (int j = i+1; j < num; j++)
{
if (temp >= ar[j])
{
temp = ar[j];
index = j;
}
}
ar[index] = ar[i];
ar[i] = temp;
}
show_ar(ar);
return 0;
}
void show_ar(int * a)
{
for (int i = 0; i < num; i++)
{
if (a[i] < 10)
cout << " ";
cout << a[i] << " ";
if ((i + 1) % 10 == 0)
cout << endl;
}
}
運行結果如下:

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/270038.html
標籤:新手樂園
