排序算法

1 冒泡排序
int SortBubble(int* array,int size)
{
	if (NULL == array ||
		0 >= size) {
	    return 1;
	}
	for (int count = 1;count < size;count++) {
		for (int j = 0;j < size - count;j++) {
			if ( array[j] > array[j+1] ) {
				int tmp = array[j];
				array[j] = array[j+1];
				array[j+1] = tmp;
			}
		}
	}
	return 0;
}

2 选择排序
int SortSelect(int* array, int size)
{
	if (NULL == array ||
		0 >= size) {
	    return 1;
	}
	for (int count = 1;count < size;count++) {
		int key = array[count - 1];
		for (int j = count;j < size;j++) {
			if ( array[j] < key) {
				int tmp = key;
				array[count - 1] = array[j];
				key = array[count - 1];
				array[j] = tmp;
			}
		}
	}
	return 0;
}

3 插入排序
int SortInsert(int* array, int size)
{
	if (NULL == array ||
		0 >= size) {
	    return 1;
	}
	//Consider the first element is sorted,then start from the second element to insert.
	int start = 0;
	for(int i = start + 1;i < size;i++)
	{
		int cur = array[i];
		int j = i - 1;
		//Compare the current element to insert with the sorted elements which start from the last element of current element.
		while((j >= start) && 
			  (array[j] > cur)) {
			array[j+1] = array[j]; 
			j--;
		}
		array[j+1] = cur;
	}
	return 0;
}

4 快速排序
int SortQuick(int* array, int size)
{
    if (NULL == array) {
        return 1;
    }

    if (2 > size) return 1;

    int start = 0;
    int end = size - 1;
    int key = array[start];

    while (start < end) { //Divide the unsorted part into smaller and bigger parts based on key value until start = end 
        while (start < end) {
            if (array[end] < key) {
                array[start] = array[end]; //After this statement, array[end] is empty. The element with bigger index than end must be bigger than key.
                start++;//The unsorted area is from start++ to end now.
                break;
            }
            end--;
        }

        //If code can reach here, then either array[end] is empty or start=end.
        //If array[end] is empty, then sort the area from start to end based on key.
        while(start < end) {
            if (array[start] > key) {
                array[end] = array[start];
                end--;//The unsorted area is from start to end-- now.
                break;
            }
            start++;
        }
    }

    //start must be EQUAL to end and array[start] is empty now,then assign the key value to it.
    array[start] = key;

    SortQuick(array, start);
    SortQuick(array+start+1, size - start - 1);

    return 0;
}
      


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值