Introduction:
Sort array in ascending order.
Sorting array in c++ refers to arranging and sorting of numbers in ascending and descending order. Ascending order is default sort() function for sorting numbers. There are various function for c++ sort
through which we can sort numbers for example bubble sort , merge sort , heap sort , insertion sort , selection sort and many more
Sort array in ascending order in C++ using the bubble algorithm
#include <iostream>
using namespace std;
int main() {
const int SIZE = 10;
int arr[SIZE] = {5, 2, 9, 1, 8, 3, 7, 6, 4, 0};
// Bubble sort algorithm
for (int i = 0; i < SIZE-1; i++) {
for (int j = 0; j < SIZE-i-1; j++) {
if (arr[j] > arr[j+1]) {
// swap elements
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
// print sorted array
for (int i = 0; i < SIZE; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
sort array in ascending order
Explanation:
The program first declares an integer array of size 10 and initializes it with some random values.
With the help of the bubble sort algorithm to sort array in ascending order. The bubble sort algorithm compares adjacent elements of the array and exchange them if they are not in manner. This process is repeated until the array is sorted
After all, the program will print the sorted array to the console
Note: this program is a basic example of sorting an array. There are many sorting algorithms available which are more efficient and can sort large arrays faster than the bubble sort
here are some more efficient sorting algorithms that can be used for sort array in ascending order in C++
In this selection sort, algorithm can select the minimum or maximum element from the portion of the array and in the beginning of the array. The process will be on repeat until the array is stored
: void selectionSort(int arr[], int n) {
int minIndex;
for (int i = 0; i < n-1; i++) {
minIndex = i;
for (int j = i+1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
swap(arr[i], arr[minIndex]);
}
}
Quick sort : Quick sort is a divided and conquer algorithm that partitions the array into smaller sub arrays based on it pivot element and then recursively sorts the sub –arrays
void insertionSort(int arr[], int n) {
int key, j;
for (int i = 1; i < n; i++) {
key = arr[i];
j = i-1;
while (j >= 0 && arr[j] > key) {
arr[j+1] = arr[j];
j--;
}
arr[j+1] = key;
}
}
This kind of algorithms are more efficient than the bubble sort for large arrays. In this the choice of which algorithms to used depends on the specific
This is how to sort array in ascending order
Write C++ program to insert an element in array
Write Sum of Elements in an array in C++ Programming