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};
  8. int temp=0;
  9.  
  10. int key;
  11. cout <<"Enter the value you would like to be the key for the linear search: ";
  12. cin >> key; //Key value used in linear search, this will become more valuable when we get into classes / objects
  13. for (int i=0; i<size; i++){//iterate through the loop
  14. if (anArray[i] == key){//if the value of i in the array is == to key
  15. cout << "\nThe position of " << key << " is at position " << i << " in the array."<<endl <<endl; //We print out where that key is in the array
  16. break;
  17. }
  18. else{//Else, we don't do anything.
  19. //null
  20. }
  21. }
  22.  
  23.  
  24. bool swapped=true;
  25. while(swapped){
  26. swapped=false;
  27. for(int i=1; i<size; i++){
  28. if (anArray[i] < anArray[i-1]){
  29. temp = anArray[i];
  30. anArray[i] = anArray[i-1];
  31. anArray[i-1]= temp;
  32. swapped = true;
  33. }
  34. }
  35. }
  36. cout << "\n\n";
  37. for (int i=0; i<size; i++){
  38. cout << anArray[i] << endl;
  39. }
  40. cout << "\n\n";
  41.  
  42.  
  43. int val;
  44. cout << "What is the value you're searching for? ";
  45. cin >> val;
  46.  
  47. int max= 8, min=0, middle;
  48. bool found = false;
  49.  
  50. while(min <= max){
  51. //Binary sort!
  52. // 10,20,30,40,50,60,70,80,90
  53. // 0 1 2 3 4 5 6 7 8
  54. // 0 4 8
  55. // 0 5 6 8
  56.  
  57.  
  58. // 0 + 8 / 2= 4
  59. //5 + 8 = 13 / 2 = 6.5 = 6
  60. middle = ((max+min)/2);
  61. if (anArray[middle] < val){
  62. min = middle+1;
  63. cout << "\nmin now equals: " << min;
  64. //min =0 first loop middle = 4 + 1 =5
  65. }
  66. if (anArray[middle] > val){
  67. max = middle-1;
  68. cout <<"\nmax now equals: "<< max;
  69. // max =8 set it to 5 (2nd iteration looking for 60
  70. }
  71.  
  72. if (anArray[middle] == val){
  73. cout << "The value: "<< val << " Was found at array location: "<< middle;
  74. found = true;
  75. break;
  76. }
  77. }
  78.  
  79.  
  80.  
  81. if (found == false){
  82. cout << "\nThe value was not found.";
  83. }
  84.  
  85.  
  86.  
  87.  
  88.  
  89.  
  90. return 0;
  91. }
  92.  
Success #stdin #stdout 0s 2728KB
stdin
60
20
stdout
Enter the value you would like to be the key for the linear search: 
The position of 60 is at position 7 in the array.



10
20
30
40
50
60
70
80
90


What is the value you're searching for? 
max now equals: 3The value: 20 Was found at array location:  1