选择排序
本人非科班出生,也未有人指导,纯属自学,难免有错误,恳请指导!
for i = 1 to A.length
min = A[i]
j = i + 1
whie j > 0
if A[j]<min
min = A[j]
k = j
j++
A[j] = A[i]
A[i] = min
最好情况 T(n) = theta(n)
最坏情况T(n) = theta(n^2)
printf("选择排序测试\n");
double arr_select[6] = {31, 41, 59, 26, 41, 58};
printf("array=");
for (int i = 0; i < 6; i ++)
{
printf("%lf ", arr_select[i]);
}
printf("\nsorted array=");
selection_sort(arr_select, 6);
for (int i = 0; i < 6; i++)
{
printf("%lf ", arr_select[i]);
}
printf("\n..........................................\n");
______________________________________________________
______________________________________________________________
选择排序
思想,每次从还未排序的子序列中选择最小(最大)的元素,排在已排序子序列中
for i = 1 to A.length
min = A[i]
j = i + 1
whie j > 0
if A[j]<min
min = A[j]
k = j
j++
A[j] = A[i]
A[i] = min
最好情况 T(n) = theta(n)
最坏情况T(n) = theta(n^2)
/*选择排序 * @param array 输入数组 * @param length 数组长度 */ void selection_sort(double array[], int length) { int i,j,k; for (i = 0; i < length; i++) { int min_value = array[i]; j = i + 1; while (j < length) { if (array[j] < min_value) { min_value = array[j]; k = j; } j++; } array[k] = array[i]; array[i] = min_value; } }
printf("选择排序测试\n");
double arr_select[6] = {31, 41, 59, 26, 41, 58};
printf("array=");
for (int i = 0; i < 6; i ++)
{
printf("%lf ", arr_select[i]);
}
printf("\nsorted array=");
selection_sort(arr_select, 6);
for (int i = 0; i < 6; i++)
{
printf("%lf ", arr_select[i]);
}
printf("\n..........................................\n");
今天又用到以前上面写的选择排序,发现有逻辑错误,就是数组前半部分需交换顺序,此时k等于某个值,而当数组后半部分不需交换顺序时,还在执行array[k] = array[i];
array[i] = min_value;
SELECTION_SORT(A) for i = 1 to A.length min = A[i] j = i + 1 k = i whie j > 0 if A[j]<min min = A[j] k = j j++ if k != i A[k] = A[i] A[i] = min
/*选择排序 * @param array 输入数组 * @param length 数组长度 */ void selection_sort(double array[], int length) { int i,j,k; for (i = 0; i < length; i++) { int min_value = array[i]; j = i + 1; k = i; while (j < length) { if (array[j] < min_value) { min_value = array[j]; k = j; } j++; } if (k != i) { array[k] = array[i]; array[i] = min_value; } } }
______________________________________________________