Recently I had an idea: I used c/c ++ to rewrite common algorithms in linux. Of course, my understanding of algorithms is limited to my skills. I cannot go beyond the foresight of my predecessors, but I still want to demonstrate it in my own way. Just entertain myself! Adhering to the principle of consistency, without making a general sense, we only demonstrate the demo of key code and the first algorithm to start the algorithm journey-Bubble sorting.
1. Edit the BubbleSort. c file, as shown in the following figure:
[Cpp] # include <stdio. h>
Void bubbleSort (int * pArr, int cnt)
{
Int I, j, tmp;
For (I = 0; I <cnt; I ++)
{
For (j = I + 1; j <cnt; j ++)
{
If (* (pArr + I)> * (pArr + j ))
{
Tmp = * (pArr + I );
* (PArr + I) = * (pArr + j );
* (PArr + j) = tmp;
}
}
}
}
Int main (void)
{
Int cnt;
Printf ("input array length: \ n ");
Scanf ("% d", & cnt );
If (cnt <1)
{
Printf ("array length must be larger 0 \ n ");
Return 1;
}
Else
{
Printf ("array length is % d \ n", cnt );
}
Int a [cnt];
Int I;
For (I = 0; I <cnt; I ++)
{
Printf ("input arr [% d] value \ n", I );
Scanf ("% d", & a [I]);
}
BubbleSort (a, cnt );
Printf ("bubblesort result: \ n ");
For (I = 0; I <cnt; I ++)
{
Printf ("% d", a [I]);
}
Printf ("\ n ");
Return 0;
}
# Include <stdio. h>
Void bubbleSort (int * pArr, int cnt)
{
Int I, j, tmp;
For (I = 0; I <cnt; I ++)
{
For (j = I + 1; j <cnt; j ++)
{
If (* (pArr + I)> * (pArr + j ))
{
Tmp = * (pArr + I );
* (PArr + I) = * (pArr + j );
* (PArr + j) = tmp;
}
}
}
}
Int main (void)
{
Int cnt;
Printf ("input array length: \ n ");
Scanf ("% d", & cnt );
If (cnt <1)
{
Printf ("array length must be larger 0 \ n ");
Return 1;
}
Else
{
Printf ("array length is % d \ n", cnt );
}
Int a [cnt];
Int I;
For (I = 0; I <cnt; I ++)
{
Printf ("input arr [% d] value \ n", I );
Scanf ("% d", & a [I]);
}
BubbleSort (a, cnt );
Printf ("bubblesort result: \ n ");
For (I = 0; I <cnt; I ++)
{
Printf ("% d", a [I]);
}
Printf ("\ n ");
Return 0;
}
2. Compile the program
[Plain] [root @ localhost gcc] # gcc-o BubbleSort. c
[Root @ localhost gcc] # gcc-o BubbleSort. c
3. Execution
[Plain] [root @ localhost gcc] #./BubbleSort
Input array length:
3
Array length is 3
Input arr [0] value
2
Input arr [1] value
1
Input arr [2] value
4
Bubblesort result:
1 2 4
[Root @ localhost gcc] #./BubbleSort
Input array length:
3
Array length is 3
Input arr [0] value
2
Input arr [1] value
1
Input arr [2] value
4
Bubblesort result:
1 2 4
Well, it's good to use your own hands and try again! Let's do this first, and continue to improve this article. Hope you can stick to it.
From the pure soul