C语言读入长度不确定的整数序列并进行排序

文章目录

效果

在这里插入图片描述

code

#include <stdio.h>
/*sizeof()运算符是有局限性的,在于它不是动态的
C/C++中,sizeof()只是运算符号,是编译的时候确定大小的。动态分配是运行过程中得到大小的,也就是说C++中new出来的内存,sizeof都无法统计的,退一步说,即使是new出来的空间也有可能失败,所以sizeof无法统计动态分配的内存大小。*/

int main() {
    
    
	void myBubbleSort(int *num_array, int size);

	while (1) {
    
    

		int num_array[1000];
		printf("input numbers you want to sort(bubble sort):\n");

		/*read in integers without size indicate:*/
		char c;//to temporary save a charactor to judge the '\n'

		int size = 0;
		//int isEof = 0;

		while ((c = getchar()) != '\n') {
    
    
			/*return the charater which is not '\n'*/
			ungetc(c, stdin);
			/*now read in the integer number:
			use the scanf("%d",&num_array[i]) to save the number to array*/
			//isEof = scanf("%d", &num_array[size++]);

		}

		//size= sizeof(num_array) / sizeof(int);
		/*invoke the sort function:*/
		myBubbleSort(num_array, size);

		/*print the sorted sequence consequence*/
		for (int i = 0; i < size; i++) {
    
    

			printf("%d ", num_array[i]);
		}

		printf("\n");
	}
}

/*the bubble sort function:*/
void myBubbleSort(int *num_array, int size) {
    
    
	void swap(int *a, int *b);

	/*we need two for loop*/
	for (int i = 0; i < size - 1; i++) {
    
    

		for (int j = 0; j < size - 1 - i; j++) {
    
    

			if (*(num_array + j) > *(num_array + j + 1)) {
    
    
				swap(num_array + j, num_array + j + 1);
			}
		}
	}
}

void swap(int *a, int *b) {
    
    
	int tmp = *a;
	*a = *b;
	*b = tmp;
}
/*
test data
5 3 7 1 9 33 66 44 333 11
9 33 66 7 1 9 33  44 34733 11
3 6  0 2 5


*/

猜你喜欢

转载自blog.csdn.net/xuchaoxin1375/article/details/114887398