Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2019
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3.  
  4. using namespace std;
  5.  
  6. void insertionSort(int x[], int n){
  7. for (int i = 1; i < n; ++i) {
  8. for (int j = i; j > 0 && x[j - 1] > x[j]; --j) {
  9. swap(x[j-1], x[j]);
  10. }
  11. }
  12.  
  13. /*
  14. int i, j;
  15. for(i = 1; i < n; i++){
  16. int temp = x[i];
  17. for (j = i-1; j >= 0 && x[j - 1] > temp; j--){
  18. x[j] = x[j - 1];
  19. if(x[j] > temp){
  20. x[j+1] = x[j];
  21. }else{
  22. x[j+1] = temp;
  23. break;
  24. }
  25.  
  26. }
  27. x[j] = temp;
  28. }
  29. */
  30. }
  31.  
  32. void display(int x[], int length){
  33. for(int i = 0; i < length; i++){
  34. cout << x[i] << " ";
  35. }
  36. cout << endl;
  37. }
  38.  
  39. int main() {
  40. int count, index = 0, temp;
  41. ifstream data("hw3.dat");
  42. if (data.is_open()) {
  43. cout << endl << "File opened successfully." << endl;
  44. }
  45. data >> count;
  46. cout << "Number of elements: " << count << endl << "========================" << endl;
  47. int *arr = new int[count];
  48. cout << "Original data: ";
  49. while (data >> temp) {
  50. arr[index] = temp;
  51. temp = 0;
  52. index++;
  53. }
  54. //int test [] = {8, 1, 11, 2, 10, 9, 3, 4, 7, 6, 5};
  55. display(arr, count);
  56. insertionSort(arr, count);
  57. cout << "After sorting: ";
  58. display(arr, count);
  59. cout << endl;
  60. delete[] arr;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement