这或许是东半球讲十大排序算法最好的一篇文章(c++版程序)

参考:https://juejin.cn/post/6844903863288332302

冒泡排序代码:

include

include

using namespace std;

//冒泡排序数组方式
int bubblesort(int a[], int num)
{
int i=0,j=0;
int tmp = 0;

for (i=0; i<num-1;i++)
{
    for(j=0; j <num-1-i;j++)
    {
        if(a[j] < a[j+1])
        {
            tmp = a[j];
            a[j] = a[j+1];
            a[j+1] = tmp;
        }
    }
}
return 0;

}

//vector方式
void bubble(vector &nums)
{
int size = nums.size();
for(int i=0; i< size-1;i++)
for(int j=0; j < size-i-1;j++)
{
if(nums[j] <nums[j+1])
{
swap(nums[j], nums[j+1]);
}
}
}
//选择排序
void selectSort(int a[], int num)
{
int min_flag = 0;//最小值下标
int tmp = 0;
for (int i = 0; i < num; i++)
{
min_flag = i;
for (int j = i+1 ; j< num; j++)
{
if (a[j] < a[min_flag])
{
min_flag = j;
}
}
tmp = a[i];
a[i] = a[min_flag];
a[min_flag] = tmp;
}
}

//插入排序
void insertSort(int a[], int num)
{
int i,j = 0;
int value = 0;
for (i=1; i< num; i++)
{
value = a[i];//要比较的元素
for (j= i-1; j>=0; j--)//插入的位置
{
if(a[j] > value)
{
a[j+1] = a[j];
}
else
{
break;
}
}
a[j+1] = value;//插入数据
}
}

//希尔排序
void hillSort(int a[], int num)
{
int gap , i , j = 0;
gap = num/2;
while(gap>0)
{
for (i = gap; i< num ; i++)
{
int val = a[i];
j = i-gap;
while(val < a[j] && j>=0)
{
a[j+gap] = a[j];
j -= gap;
}
a[j + gap] = val;
}

	gap /= 2;
}

}

int main() {

int nums[6] = {2,3,4,7,9,0};
for (int i= 0; i < 6; i++)
{
    cout <<"before num:" << nums[i] <<endl;
}
//(void)bubblesort(nums, 6);
 (void)insertSort(nums,6);
for (int i= 0; i < 6; i++)
{
    cout <<"after num:" << nums[i]<<endl;
}
cout  << "test\n";
cout << "vector sort :" <<endl;

vector<int> tmp{3,90,34,5};
for(auto iter= tmp.begin(); iter != tmp.end();iter++)
{
    cout << "before sort, i:" << *iter << endl;
}

bubble(tmp);
vector<int>::iterator it;

for(it= tmp.begin(); it != tmp.end();it++)
{
    cout << "after sort, i:" << *it << endl;
}


return 0;

}

posted @ 2020-12-22 18:23  wulongming88  阅读(152)  评论(0编辑  收藏  举报