日常编程笔记 | 2022.9.30 | BubbleSort

冒泡排序

巨小数字

在这里插入图片描述
为什么会出现第一个数字呢?
我生成随机数的代码如下

在这里插入图片描述
发现元凶了!给SortedIndex赋的初值是N,那么比较的时候数组下标越界了!然后把原来的最后一位扔掉了TAT

SortedIndex 的无效优化

在这里插入图片描述这里的SortedIndex始终让j的扫描范围为整个数列
改进后

在这里插入图片描述

C源码
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define N 10 //the size of the array

//bubble sort and its test program

void BubbleSort(int* array)
{
	int isSorted = 1;//to decide wether the array is ordered
	int SortedIndex = N - 1;//to record the left sorted index
	int i,j;
	int temp;
	int thisIndex;
		
	for(i = 0; i < N; i++)//control the loop times
	{
		isSorted = 1;//initialize the state
		for(j = 0; j < SortedIndex; j++)//SortedIndex is the right boundary of sorted elements
										//which can spare you of a lot trouble of sorting ordered array 
		{
			if(array[j] > array[j + 1])
			{
				isSorted = 0;//the array is not in order yet
				temp = array[j];//exchange the order
				array[j] = array[j + 1];
				array[j + 1] = temp;
				thisIndex = j;
			}
					
		}
		if(isSorted)
			break; //if the array is already in order, then stop the loop
		SortedIndex = thisIdex;//renew the right boundary of sorted elements
				
	}
			
}


int main()
{
	srand((unsigned int)time(0));//initialize the seed
	
	int i;
	int*array = (int*)malloc(sizeof(int)*N);
	
	for(i = 0; i < N; i++)
	{
		array[i] = rand()%100 - 50;//to generate random number from -50 to 50 
	}
	
	BubbleSort(array);
	
	for(i = 0; i < N; i++)
	{
		printf("%d ",array[i]);
		
	}
		
	return 0;
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值