Algorithms - Bubble Sort

Standard bubble sort

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<malloc.h>
#include <string.h>

int BubbleSort(int *p, int n)
{
int i, j,temp;
for(i=0;i<n-1;i++)
for (j = 0; j < n-1-i; j++)
{
if (p[j] > p[j+1])
{
temp = p[j];
p[j] = p[j+1];
p[j+1] = temp;
}
}
}

int dayin(int *q,int len)
{
int i;
for (i = 0; i < len; i++)
{
printf("%d ", q[i]);
}


}

void main()
{
int a[] = { 5,2,4,50,100,3,6,7,8,9 };
int len = sizeof(a) / sizeof(a[0]);
BubbleSort2(a, len);
dayin(a, len);
char b[] = {"sdsdsdsd"};
printf("\n%d", strlen(b));
}

 

Optimization of a
Suppose we now sorted ar [] = {1,2,3,4,5,6,7,8,10,9} this set of data, according to the above ordering, ordering after the first pass 10 and 9 exchange has been ordered, the next eight times ordering is superfluous, nothing to do. So we can add a mark in the local exchange, if the exchange is not the sort that trip element, indicating that this set of data has been ordered, no longer continue.

 

int BubbleSort1(int *p, int n)//优化1
{
int i, j, temp,flag;
for (i = 0; i < n - 1; i++)
{
flag = 0;
for (j = 0; j < n - 1 - i; j++)
{
if (p[j] > p[j + 1])
{
temp = p[j];
p[j] = p[j + 1];
p[j + 1] = temp;
flag = 1;
}
}
if (flag == 0)
{ break; }
}

}

 

 

 

Optimization of two
optimization applies only to a contiguous ordered integrally unordered data (for example: 1, 2, 3, 4, 7,6,5). But for most of the front and back of the disorder is ordered less than half of the data section (1,2,5,7,4,3,6,8,9,10) sorting efficiency is not significant for the types of data, we can continue to optimize. We can only note the location of the last exchange, the exchange is not behind, it must be ordered, then the next time ordering from a comparison to the end of the last recorded position can be.

int BubbleSort2(int *p, int n)//优化2
{
int i, j, temp, flag;
int k = n - 1;
int k0 = 0;
for (i = 0; i < n - 1; i++)
{
flag = 0;

for (j = 0; j < k; j++)
{
if (p[j] > p[j + 1])
{
temp = p[j];
p[j] = p[j + 1];
p[j + . 1 ] = TEMP; 
In Flag = . 1 ; 
kO = J; // calculate the position of the last exchange 
} 
} 
K = kO; // the next comparison to the position of the last exchange 
IF (In Flag == 0 ) 
{ 
return ; 
} 
} 

}

 

Guess you like

Origin www.cnblogs.com/cyyz-le/p/10987727.html