Sorting - bubble sort
来源:互联网 发布:淘宝的火麻叶是真的么 编辑:程序博客网 时间:2024/06/07 22:40
#include "stdio.h"#include "string.h"#define MAX_LIST 50typedef struct _SqList { int data[MAX_LIST]; int length;}SqList;void swap( SqList* L, unsigned index1, unsigned index2 ){ if( index1 >= L->length || index2 >= L->length ) return; if( index1 == index2 ) return; L->data[index1] = L->data[index1] ^ L->data[index2]; L->data[index2] = L->data[index1] ^ L->data[index2]; L->data[index1] = L->data[index1] ^ L->data[index2];}enum BUBBLE_SORT_METHOD { PLAIN, FLAG };//original bubble sort algorithmvoid BubbleSortPlain(SqList* L){ int i, j; for( i = 0; i < L->length - 1; i++ ) { //every outer loop pick the smallest from the rear of the array for( j = L->length-2; j >= i; j-- ) { //compare adjacent elements and get the smaller move forward if( L->data[j] > L->data[j+1] ) swap(L, j, j+1 ); } }}//Optimized with a flag indicating should there any swapping occurred in the previous loop//if there is no swapping, loop should exit prematurelyvoid BubbleSortFlag(SqList* L){ bool flag = true; int i, j; for( i = 0; flag && i < L->length - 1; i++ ) { //every outer loop pick the smallest from the rear of the array for( j = L->length-2; j >= i; j-- ) { flag = false; //compare adjacent elements and get the smaller move forward if( L->data[j] > L->data[j+1] ) { swap(L, j, j+1 ); flag = true; } } }}void BubbleSort( SqList* L, BUBBLE_SORT_METHOD bs ){ if( bs == PLAIN ) { BubbleSortPlain( L ); } else { BubbleSortFlag( L ); }}int main(){ SqList d; int intarr[] = {1,10,23,48,65,31,-21,9,88,100}; memcpy( d.data, intarr, sizeof(intarr)); d.length = sizeof(intarr)/sizeof(int); int index = 0; printf("Original array:\n"); for( ; index < d.length; index++ ) printf(" %d", d.data[index] ); printf("\nBubble sort...\n"); BubbleSort( &d, FLAG ); for( index = 0; index < d.length; index++ ) printf(" %d", d.data[index] ); printf("\n"); return 0;}
0 0
- Sorting - bubble sort
- Sorting Algorithm-Bubble Sort
- Internal Sorting: Bubble sort: Sorting by Exchanging
- bubble sorting
- 【Data Structures】 7. Simple Sorting—Bubble Sort, Selection Sort, and Insertion Sort
- Bubble sort
- Bubble Sort
- bubble sort
- Bubble Sort
- Bubble Sort
- bubble sort
- Bubble Sort
- Bubble Sort
- Bubble Sort
- Bubble Sort
- Bubble Sort
- Bubble Sort
- Bubble Sort
- iOS笔记:第七篇 C语言 数组
- 5-线程范围内共享变量
- 梳理《前目的地》
- poj 3070 Fibonacci 【矩阵快速幂】
- Python线程指南
- Sorting - bubble sort
- Android异步更新UI-线程池-Future-Handler实例分析
- FFmpeg源代码简单分析:makefile
- Android应用开发相关下载资源(2014/12/14更新)
- 基于mykernel实现的时间片轮转调度代码分析
- Android工程文件不能自动生成R文件
- Number of 1 bits(算法练习)
- Palindrome Number
- 《大型网站系统与JAVA中间件实践》读书笔记