- 使用 C 语言的 DSA 教程
- 使用 C 语言的 DSA - 主页
- 使用 C 语言的 DSA - 概述
- 使用 C 语言的 DSA - 环境
- 使用 C 语言的 DSA - 算法
- 使用 C 语言的 DSA - 概念
- 使用 C 语言的 DSA - 数组
- 使用 C 语言的 DSA - 链表
- 使用 C 语言的 DSA - 双向链表
- 使用 C 语言的 DSA - 循环链表
- 使用 C 语言的 DSA - 栈
- 使用 C 语言的 DSA - 解析表达式
- 使用 C 语言的 DSA - 队列
- 使用 C 语言的 DSA - 优先级队列
- 使用 C 语言的 DSA - 树
- 使用 C 语言的 DSA - 哈希表
- 使用 C 语言的 DSA - 堆
- 使用 C 语言的 DSA - 图
- 使用 C 语言的 DSA - 搜索技术
- 使用 C 语言的 DSA - 排序技术
- 使用 C 语言的 DSA - 递归
- 使用 C 语言的 DSA 实用资源
- 使用 C 语言的 DSA - 快速指南
- 使用 C 语言的 DSA - 实用资源
- 使用 C 语言的 DSA - 讨论
使用 C 语言的 DSA - 选择排序
概述
选择排序是一种简单的排序算法。这种排序算法是一种基于比较的原址算法,其中列表被分为两部分,左端的已排序部分和右端的未排序部分。最初,已排序部分为空,未排序部分是整个列表。
从未排序数组中选择最小元素并与最左边的元素进行交换,该元素成为已排序数组的一部分。此过程继续将未排序数组的边界向右移动一个元素。
该算法不适用于大型数据集,因为它的平均和最坏情况复杂度都是 O(n2),其中 n 是项数。
伪代码
Selection Sort ( A: array of item)
procedure selectionSort( A : array of items )
int indexMin
for i = 1 to length(A) - 1 inclusive do:
/* set current element as minimum*/
indexMin = i
/* check the element to be minimum */
for j = i+1 to length(A) - 1 inclusive do:
if(intArray[j] < intArray[indexMin]){
indexMin = j;
}
end for
/* swap the minimum element with the current element*/
if(indexMin != i) then
swap(A[indexMin],A[i])
end if
end for
end procedure
示例
#include <stdio.h>
#include <stdbool.h>
#define MAX 7
int intArray[MAX] = {4,6,3,2,1,9,7};
void printline(int count){
int i;
for(i=0;i <count-1;i++){
printf("=");
}
printf("=\n");
}
void display(){
int i;
printf("[");
// navigate through all items
for(i=0;i<MAX;i++){
printf("%d ",intArray[i]);
}
printf("]\n");
}
void selectionSort(){
int indexMin,i,j;
// loop through all numbers
for(i=0; i < MAX-1; i++){
// set current element as minimum
indexMin = i;
// check the element to be minimum
for(j=i+1;j<MAX;j++){
if(intArray[j] < intArray[indexMin]){
indexMin = j;
}
}
if(indexMin != i){
printf("Items swapped: [ %d, %d ]\n" ,intArray[i],intArray[indexMin]);
// swap the numbers
int temp=intArray[indexMin];
intArray[indexMin] = intArray[i];
intArray[i] = temp;
}
printf("Iteration %d#:",(i+1));
display();
}
}
main(){
printf("Input Array: ");
display();
printline(50);
selectionSort();
printf("Output Array: ");
display();
printline(50);
}
输出
如果我们编译并运行上述程序,它会产生以下输出 −
Input Array: [4, 6, 3, 2, 1, 9, 7] ================================================== Items swapped: [ 4, 1 ] iteration 1#: [1, 6, 3, 2, 4, 9, 7] Items swapped: [ 6, 2 ] iteration 2#: [1, 2, 3, 6, 4, 9, 7] iteration 3#: [1, 2, 3, 6, 4, 9, 7] Items swapped: [ 6, 4 ] iteration 4#: [1, 2, 3, 4, 6, 9, 7] iteration 5#: [1, 2, 3, 4, 6, 9, 7] Items swapped: [ 9, 7 ] iteration 6#: [1, 2, 3, 4, 6, 7, 9] Output Array: [1, 2, 3, 4, 6, 7, 9] ==================================================
dsa_using_c_sorting_techniques.htm
广告