The application of pointers in C language algorithm
The first thing to say is sort
The sorting is basically divided into 5 kinds
Insert Sort, select sort, swap sort, merge sort, assign sort
First, 7, 8, bubble sort.
#include <iostream>
#include <cstdio>
using namespace Std;
void Bubblesort (int *array, int n)
{
int A;
for (int i = n; i > 0; i.)
{
for (int j = 0; J < i; ++j)
{
if (* (array + j) > * (array + j + 1)
{
A = * (Array + j);
* (array + j) = * (array + j + 1);
* (Array +j + 1) = A;
}
}
}
}
int main ()
{
int array[8] = {5, 9, 2, 16, 7, 4, 12, 15};
printf ("Array to be sorted as: \ n");
for (int i = 0; i < 8; ++i)
printf ("%d", * (Array + i));
Bubblesort (Array, 8);
printf ("\ n bubble sorted array is: \ n");
for (int j = 0; J < 8; ++j)
{
printf ("%d", * (Array + j));
}
return 0;
}
Improvement of bubble sort 1
Through the general bubble sort, it is easy to draw a conclusion that
It is no longer necessary to exchange from R at the end of a trip, so it is already sorted from Array[r + 1] to array[n-1].
So as long as the comparison to the position of R can be.
#include <iostream>
#include <cstdio>
using namespace Std;
void Bubble (int *array, int n)
{
int bound = n;
int m, I;
int A; Intermediate variables for swapping
while (bound! = 0)
{
m = 0;
for (i = 0; i < bound; i++)
{
if (* (array + i) > * (array + i + 1)
{
A = * (Array + i);
* (array + i) = * (array + i + 1);
* (Array + i + 1) = A;
m = i;
}
}
bound = m;
}
}
int main ()
{
int array[9] = {36, 80, 15, 26, 33, 2, 96, 46, 83};
int i;
printf ("The array to be sorted is: \ n");
for (int i = 0; i < 9; ++i)
{
printf ("%d", * (Array + i));
}
Bubble (Array, 9);
printf ("\ n" the sorted array is: \ n ");
for (int j = 0; J < 9; ++j)
{
printf ("%d", * (Array + j));
}
return 0;
}
Bubble Sort Change 2
Two-Way foaming
It is every trip to find the largest place at the bottom to find the smallest place on top.
Save time
#include <iostream>
#include <cstdio>
using namespace Std;
void twobubble (int *array, int n)
{
int boundmin = 0;
int boundmax = n;
int mmin, Mmax;
int A;
This makes the foaming heavy sinking
while (Boundmin < Boundmax)
{
mmin = 0;
Mmax = 0;
for (int i = boundmin; i < Boundmax; i++)
{
if (* (array + i) > * (array + i + 1)
{
A = * (Array + i);
* (array + i) = * (array + i + 1);
* (Array + i + 1) = A;
Mmax = i;
}
}
if (Mmax = = 0)
Break
Boundmax = Mmax;
for (int i = boundmax-1; i > boundmin; i--)
{
if (* (array + i) < * (array + i-1))
{
A = * (Array + i);
* (array + i) = * (array + i-1);
* (Array + i-1) = A;
Mmin = i;
}
}
if (mmin = = 0)
Break
Boundmin = Mmin;
}
}
int main ()
{
int array[9] = {36, 80, 14, 26, 33, 4, 96, 28, 83};
printf ("The array to be sorted is \ n");
for (int i = 0; i < 9; ++i)
{
printf ("%d", * (Array + i));
}
Twobubble (Array, 9);
printf ("\ n" the sorted array is: \ n ");
for (int j = 0; J < 9; ++j)
{
printf ("%d", * (Array + j));
}
return 0;
}
C Pointer Programming path---seventh notes