第一个是选择排序法,第二个是起泡排序法,第二种排序输出结果总是多出一个0,帮忙看一下!
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int array[10];
void select_sort(int array[]);
void bubble_sort(int array[]);
int main(){
srand((unsigned)time(NULL));
for (int i = 0; i < 10; i++)
{
array[i] = rand()%100;
cout<<array[i]<<',';
}
cout<<'\n';
select_sort(array);
cout<<'\n';
bubble_sort(array);
}
/**
*
* 1.首先在未排序序列中找到最小元素,存放到排序序列的起始位置,
* 2.再从剩余未排序元素中继续寻找最小元素,然后放到已排序序列的末尾。
* 3 以此类推,直到所有元素均排序完毕
*
*/
void select_sort(int array[]){
int i,j,t ;
for ( i = 0; i < 10 -1 ; i++)
{
for ( j = i+1; j < 10; j++)
{
if (array[j] < array[i])
{
t = array[j];
array[j] = array[i];
array[i] = t;
}
}
}
cout<<"the select_sort results:";
for ( i = 0; i < 10; i++)
{
cout<<array[i]<<',';
}
}
/**
* 冒泡排序
* 1. 从当前元素起,向后依次比较每一对相邻元素,若逆序则交换
* 2. 对所有元素均重复以上步骤,直至最后一个元素
* 3.相邻元素比较,若逆序则交换(升序为左大于右,降序反之)
*/
void bubble_sort(int array[]){
int i,j,t;
for ( j = 0; j < 10 -1 ; j++)/* 外循环为排序趟数,len个数进行len-1趟 */
{
for ( i = 0; i < 10-1 -j; i++)/* 内循环为每趟比较的次数,第i趟比较len-i次 */
{
if (array[i]>array[i+1])/* 相邻元素比较,若逆序则交换(升序为左大于右,降序反之) */
{
t = array[i];
array[i] = array[i+1];
array[i+1] = t;
}
}
}
cout<<"the bubble_sort results:";
for ( i = 0; i < 10; i++)
{
cout<<array[i]<<',';
}
cout<<'\n';
}
i<9-j
void bubbleSort (elemType arr[], int len) {
elemType temp;
int i, j;
for (i=0; i<len-1; i++) /* 外循环为排序趟数,len个数进行len-1趟 */
for (j=0; j<len-1-i; j++) { /* 内循环为每趟比较的次数,第i趟比较len-i次 */
if (arr[j] > arr[j+1]) { /* 相邻元素比较,若逆序则交换(升序为左大于右,降序反之) */
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
#include
#include
#include
using namespace std;
int array[10];
void select_sort(int array[]);
void bubble_sort(int array[]);
int main()
{
srand((unsigned)time(NULL));
for(int i=0;i<10;i++)
{
array[i]=rand()%100;
cout<<array[i]<<'\0';
}
cout<<'\n';
select_sort(array);
cout<<'\n';
bubble_sort(array);
return 0;
}
void select_sort(int array[])
{
int i,j,k,t;
for(i=0;i<9;i++)
{
for(j=i+1;j<10;j++)
{
if (array[j]<array[i])
{
t=array[j];
array[j]=array[i];
array[i]=t;
}
}
}
cout<<"the select_sort results:";
for(i=0;i<10;i++)
{
cout<<array[i]<<'\0';
}
}
void bubble_sort(int array[])
{
int i,j,t;
for(j=0;j<10;j++)
{
for(i=0;i<10-j;i++)
{
if(array[i]>array[i+1])
{
t=array[i];
array[i]=array[i+1];
array[i+1]=t;
}
}
}
cout<<"the bubble_sort results:";
for(i=0;i<10;i++)
{
cout<<array[i]<<'\0';
}
}