A sorting function in C++ that uses a bubble sort algorithm.
Sorting in C++.
Date Created:Friday December 29th, 2006 03:41 AM
Date Modified:Monday October 27th, 2008 09:13 PM
#include <iostream>
using namespace std;
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int nMyArray[15];
int i;
int j;
for ( i = 0; i < 15; i++ ) {
nMyArray[i] = rand()%100;
}
for ( i = 0; i < 14 i++ ) {
for ( j = i + 1; j < 15 j++ ) { // this for loop starts out at the next element of the array
if (nMyArray[i] < nMyArray[j]) { // checks to see which element is higher in value
swap(&nMyArray[i], &nMyArray[j]); // swap values
}
}
}
for ( i = 0; i < 15; i++ ) {
cout << nMyArray[i] << endl;
}
return 0;
}
#include <iostream>
using namespace std;
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
// these both work inputarray[] = *inputarray and both are pointers.
//void sortarray(int inputarray[], int size) {
void sortarray(int *inputarray, int size) {
int i;
int j;
for ( i = 0; i < size - 1; i++ ) {
for ( j = i + 1; j < size; j++ ) {
if ( inputarray[i] < inputarray[j] ) {
swap(&inputarray[i], &inputarray[j]);
}
}
}
}
int main() {
int anMyArray[15];
int i;
for ( i = 0; i < 15; i++ ) {
anMyArray[i] = rand()%100;
cout << anMyArray[i] << endl;
}
cout << "sort and swap" << endl;
sortarray(anMyArray,15);
for ( i = 0; i < 15; i++ ) {
cout << anMyArray[i] << endl;
}
return 0;
}
/*
Returns:
83
86
77
15
93
35
86
92
49
21
62
27
90
59
63
sort and swap
93
92
90
86
86
83
77
63
62
59
49
35
27
21
15
*/
Downloads:
Download: function_part_1.cpp 665 B
Download: function_part_2.cpp 989 B
Please login or Click Here to register for downloads
Sort Function by Dan Lynch
is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
Based on a work at www.3daet.com
Permissions beyond the scope of this license may be available at http://www.3daet.com
