As for your implementation of bubble sorting:
- your
scanf_s in the first for loop always reads the number into the first position of the array. - your
printf in the last for loop expects an integer, but you specify the address.
To prevent the console from disappearing, you can replace getchar() with system("pause") , although this is not portable.
By fixing these things, bubble sorting works for me:
#include "stdafx.h" #include "String.h" #include <iostream> using namespace std; #include <string.h> int main() { int array[100], n, c, d, swap; printf("enter numbers of elements\n"); scanf_s("%d",&n); printf("enter %d integers\n", n); for (c = 0; c < n; c++) { scanf_s("%d", &array[c]); } for (c = 0; c < (n - 1); c++) { for (d = 0; d < n - c - 1; d++) { if (array[d] > array[d + 1]) { swap = array[d]; array[d] = array[d + 1]; array[d + 1] = swap; } } } printf("sorted list in ascending order:\n"); for (c = 0; c < n; c++){ printf("%d\n", array[c]); } system("pause"); return 0; }
source share