Last active
September 28, 2019 12:37
-
-
Save Eyongkevin/63ba4af09aeb737ffea05a157689ee25 to your computer and use it in GitHub Desktop.
c++ sorting 5 numbers using only if-statements
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include<iostream> | |
| void swap(int& a, int& b){ | |
| // Swap 2 numbers using a temporary variable. | |
| int temp; | |
| temp = a; | |
| a = b; | |
| b = temp; | |
| } | |
| int* sort(int a[]){ | |
| // Part a | |
| if(a[1] < a[0]) | |
| swap(a[1],a[0]); | |
| if(a[2] < a[1]){ | |
| swap(a[2],a[1]); | |
| if(a[1] < a[0]) | |
| swap(a[1],a[0]); | |
| } | |
| // Part b | |
| if(a[3] < a[2]){ | |
| swap(a[3], a[2]); | |
| if(a[1] < a[0]) | |
| swap(a[1],a[0]); | |
| if(a[2] < a[1]){ | |
| swap(a[2],a[1]); | |
| if(a[1] < a[0]) | |
| swap(a[1],a[0]); | |
| } | |
| } | |
| // Part c | |
| if(a[4] < a[3]){ | |
| swap(a[4],a[3]); | |
| if(a[3] < a[2]){ | |
| swap(a[3], a[2]); | |
| if(a[1] < a[0]) | |
| swap(a[1],a[0]); | |
| if(a[2] < a[1]){ | |
| swap(a[2],a[1]); | |
| if(a[1] < a[0]) | |
| swap(a[1],a[0]); | |
| } | |
| } | |
| } | |
| return a; | |
| } | |
| // Testing the algorithm | |
| int main() | |
| { | |
| int a[] = {4,5,7,9,6}; | |
| int* b = sort(a); | |
| for(int i=0; i<5; i++) | |
| std::cout<<b[i]<<" "; | |
| std::cout<<std::endl; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment