# Sorting Array Help!

 Savad Dekrup · November 16, 2014 Hello, programmers and coders. I need some help. I was reading a tutorial on learncpp.com.And something stuck me. SORTING ARRAY! Can anyone please explain, step by step how this work would be appreciated. I tried to debug with Visual C++ Express, but it no uses. I'm doom. Thanks for your helping! xD #happyCoding``#include #include using namespace std;int main(){ const int nSize = 5; int anArray[nSize] = { 30, 50, 20, 10, 40 };  // Step through each element of the array for (int nStartIndex = 0; nStartIndex < nSize; nStartIndex++) { // nSmallestIndex is the index of the smallest element // we've encountered so far. int nSmallestIndex = nStartIndex;  // Search through every element starting at nStartIndex+1 for (int nCurrentIndex = nStartIndex + 1; nCurrentIndex < nSize; nCurrentIndex++) { // If the current element is smaller than our previously found smallest if (anArray[nCurrentIndex] <= anArray[nSmallestIndex]) // Store the index in nSmallestIndex nSmallestIndex = nCurrentIndex; }  // Swap our start element with our smallest element swap(anArray[nStartIndex], anArray[nSmallestIndex]); }}``Even with comments, I don't know how it works. D;

## Replies

 Chris Olson · November 20, 2014 ill try to explain it the best way i can, and i believe this is the best way to learn, and not just take advantage of built in code...So what this algorithm is doing is initializing an array and defining a constant to use.for (int nStartIndex = 0; nStartIndex < nSize; nStartIndex++) { // nSmallestIndex is the index of the smallest element // we've encountered so far. int nSmallestIndex = nStartIndex;<-- this line initializes the first element of the array as the smallest (index 0) which is 30... then this next for loopfor (int nCurrentIndex = nStartIndex + 1; nCurrentIndex < nSize; nCurrentIndex++)<-- since we already have the first index saved as the smallest, we then start 1 plus that index so we can test index 1, then 2, then 3, then 4 { // If the current element is smaller than our previously found smallest if (anArray[nCurrentIndex] <= anArray[nSmallestIndex])<-- this compares the current index with the first index and tests if it is greater than or less than the first index, if it is smaller, it assigns it as the smallest, then tests the next index and so forth until it hits the end, you then have the smallest index // Store the index in nSmallestIndex nSmallestIndex = nCurrentIndex;Now the finalpiece of information we have is the swap() function...This is the (simplest most basic  )algorithm for swap int *temp;temp = *a;*a = *b;*b = temp; Montaser Qasem · December 2, 2014 there are many ways to sort array such as using sort function like :sort(anarray,anarray+size of the array); and it's need #include and you can just use nsted for loop in order to sort it like:for(int i=0;i
• 1

## C++

129,864 followers