第一周的工作室课题主要学习练习的内容是排序算法这一块的内容,其中我在做题时主要用到了写程序时的三个基本排序算法——直接插入排序、起泡排序、选择排序。下面为大家依次介绍:
一.直接插入排序(straight inserttion sort)。基本思想是:依次将待排序的无序区中的每一个记录插入到已排好序的有序区中,直到全部记录都排好为止,如下图所示。
代码展示:
void InsertSort(int * r,int n)
{
int i,j,temp;
for(i = 1 ; i < n ; i++){
temp = r[i];
for(j = i-1 ; j >= 0 && temp < r[j] ; j--)
{
r[j+1] = r[j];
cout << r[j] << " ";
}
r[j+1] = temp;
}
}
二.起泡排序(bubble sort)。基本思想:两两比较相邻记录,如果反序则交换,直到没有反序的记录为止,如下图所示。
代码展示:
void BubbleSort(int*r,int n)
{
int j , exchange , bound , temp;
exchange = n-1;
while(exchange != 0)
{
bound = exchange;
exchange = 0;
for(j = 0 ; j < bound ; j++)
{
if(r[j] > r[j+1])
{
cout << r[j+1] << " ";
temp = r[j];
r[j] = r[j+1];
r[j+1] = temp;
exchange = j;
}
}
}
}
三.选择排序(selection sort)。基本思想:第i趟排序在待排序序列的第ri~rn(1≤i≤n-1)中选取最小的记录,并和第i个记录交换作为有序序列的第i个记录,如下图所示。
代码展示:
void simpleSelect(int* r, int n)
{
int index, temp;
for (int i = 0 ; i < n-1; i++)
{
index = i;
for (int j = i+1; j < n; j++)
{
if (r[j] < r[index])
{
index = j;
}
}
if (index != i)
{
temp = r[i];
r[i] = r[index];
r[index] = temp;
}
}
}
*注:本文章为作者自己工作室课题学习笔记,并非学术性文章,不喜勿喷! 欢迎大佬评论指点迷津,指出不足!
*本文章参考文献:《数据结构——从概念到C++实现(第三版)》