遍历一次数据找到最小的标记起来,遍历结束后把数据放到相应位置

void SelectSort(int *a, int length)

{

if (a == NULL || length <= 0)

{

return;

}

for (int i = 0; i < length; i++)

{

int j = i;

int min = a[i];

int index = i;

while (j < length)

{

if (a[j] < min)

{

min = a[j];

index = j;

}

//if (a[j] < a[i])

//{

// int tmp = a[i];

// a[i] = a[j];

// a[j] = tmp;

//}

++j;

}

a[index] = a[i];

a[i] = min;

}

}

在一次遍历数据的时候把最大的和最小的数据标记起来在一次遍历后把最小大数据放到相应位置,并防止最大和最小的交换导致出错。

void SelectSort(int *a, int length)

{

if (a == NULL || length <= 0)

{

return;

}

int size = length - 1;

for (int i = 0; i <= size; i++,size--)

{

int min = a[i];

int max = a[size];

int minindex = i;

int maxindex = size;

int j = i;

while (j<= size)

{

if (a[j] < min)

{

min = a[j];

minindex = j;

}

if (a[j]>max)

{

max = a[j];

maxindex = j;

}

++j;

}

if (maxindex == i && minindex == size)

{

a[i] = min;

a[size] = max;

}

else

{

a[minindex] = a[i];

a[i] = min;

a[maxindex] = a[size];

a[size] = max;

}

}

}