fork download
  1. #include <iostream>
  2.  
  3. using namespace std;
  4. int main(){
  5. const int size =9;
  6. //Bubble sort and linear search.
  7. int anArray[size]={10,90,50,70,30,40,20,60,80}; //Can only set the size of an array to a const int, I did this to have a size() type usage without a vector
  8. int temp=0; //Used in the loop to swap stuff
  9.  
  10. //We declare a bool here to decide if the loop is completed or not, it's our way of running a nested loop until the nested loop no longer needs running
  11. bool swapped=true;
  12. //initialize this bool to true
  13. while(swapped){
  14. //while this bool is true
  15. swapped=false;
  16. //Set the bool to false so that if this loop doesn't hit that if statment, it won't run anymore, without this it will be an endless loop
  17. for(int i=1; i<size; i++){
  18. //iterate through the array
  19. if (anArray[i] < anArray[i-1]){
  20. //This if statement compares the values at i, and i-1, if the value at i-1 is smaller..
  21. temp = anArray[i];
  22. //We will first set temp = the current value of anArray[i]. We need to do this because we can't* swap 2 variables without something to hold one of them
  23. //* - The above is technically a lie, but for the sake of coding theory, we cannot. Any function we use will employ this same basic theory.
  24. anArray[i] = anArray[i-1];
  25. //Set the current value of anArray[i] to the value of anArray[i-1]
  26. //(so first iteration through it will be 90 vs 10, which is false, but then 50 vs 90 is not)
  27. anArray[i-1]= temp;
  28. //This completes the 'swap' when both values have been assigned to their new location.
  29. swapped = true;
  30. //Since values are still being swapped here, we set this to true again, so the loop will continue to run until it checks out as being 'false'
  31. }
  32. }
  33. }
  34.  
  35. //output loop
  36. for (int i=0; i<size; i++){
  37. cout << anArray[i] << endl;
  38. }
  39.  
  40. //linear search needs two things- for loop, and a key term
  41.  
  42. int key = 70; //Key value used in linear search, this will become more valuable when we get into classes / objects
  43.  
  44. for (int i=0; i<size; i++){//iterate through the loop
  45. if (anArray[i] == key){//if the value of i in the array is == to key
  46. cout << "\nThe position of " << key << " is at position " << i << " in the array."<<endl <<endl; //We print out where that key is in the array
  47. break;
  48. }
  49. else{//Else, we don't do anything.
  50. //null
  51. }
  52. }
  53.  
  54. return 0;
  55. }
  56.  
Success #stdin #stdout 0s 2724KB
stdin
Standard input is empty
stdout
10
20
30
40
50
60
70
80
90

The position of 70 is at position 6 in the array.