C实现的排序

1、选择排序法

#include<stdio.h>
#include<stdlib.h>

void swap(int *a,int *b)
{
	int temp;
	temp = *a;
	*a = *b;
	*b = temp;		
}
void selectsort(int *arr,int size)
{		
	int i = 0,j = 0;
	for(;i < size;i++)
	{
		int temp = arr[i];
		for(j = i;j < size;j++)
		{			
			if(arr[i] > arr[j])
			{
				swap(arr+i,arr+j);	
			}			
		}	
	}		
}

int main()
{
	
	int arr[] = {43,45,6,2,34,24,5,676,7,45};
	int i = 0;
	for(;i < 10;i++)
	{
		printf("%d\t",arr[i]);			
	}
	printf("\n");
	selectsort(arr,sizeof(arr)/sizeof(arr[0]));
	for(i = 0;i < 10;i++)
	{
		printf("%d\t",arr[i]);			
	}
	printf("\n");
	return 0;	
}
2、插入排序法
#include <stdio.h>

void println(int array[], int len)
{
    int i = 0;
    
    for(i=0; i<len; i++)
    {
        printf("%d ", array[i]);
    }
    
    printf("\n");
}

void swap(int array[], int i, int j)
{
    int temp = array[i];
    
    array[i] = array[j];
    
    array[j] = temp;
}

void InertionSort(int array[], int len) // O(n*n)
{
    int i = 0;
    int j = 0;
    int k = -1;
    int temp = -1;
    
    for(i=1; i<len; i++)
    {
        k = i;
        temp = array[k];
        
        for(j=i-1; (j>=0) && (array[j]>temp); j--)
        {
            array[j+1] = array[j];
            k = j;
        }
        
        array[k] = temp;
    }
}

int main()
{
    int array[] = {21, 25, 49, 25, 16, 8};
    int len = sizeof(array) / sizeof(*array); 
    
    println(array, len);
    
    InertionSort(array, len);
    
    println(array, len);
    
    return 0;
}
3、冒泡排序法
#include <stdio.h>

void println(int array[], int len)
{
    int i = 0;
    
    for(i=0; i<len; i++)
    {
        printf("%d ", array[i]);
    }
    
    printf("\n");
}

void swap(int array[], int i, int j)
{
    int temp = array[i];
    
    array[i] = array[j];
    
    array[j] = temp;
}

void BubbleSort(int array[], int len) // O(n*n)
{
    int i = 0;
    int j = 0;
    int exchange = 1;
    
    for(i=0; (i<len) && exchange; i++)
    {
        exchange = 0;
        
        for(j=len-1; j>i; j--)
        {
            if( array[j] < array[j-1] )
            {
                swap(array, j, j-1);
                
                exchange = 1;
            }
        }
    }
}

int main()
{
    int array[] = {21, 25, 49, 25, 16, 8};
    int len = sizeof(array) / sizeof(*array); 
    
    println(array, len);
    
    BubbleSort(array, len);
    
    println(array, len);
    
    return 0;
}

你可能感兴趣的:(C实现的排序)