Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstdlib>
- #include <ctime>
- using namespace std;
- void bubbleSort(int arr[], int n) {
- for (int i = 0; i < n - 1; i++) {
- for (int j = 0; j < n - i - 1; j++) {
- if (arr[j] > arr[j+1]) {
- swap(arr[j], arr[j+1]);
- }
- }
- }
- }
- int countOnes(int num) {
- int cnt = 0;
- while (num > 0){
- cnt += num & 1;
- num >>= 1;
- }
- return cnt;
- }
- int main() {
- srand(time(NULL));
- int n, percent;
- cout << "Enter the size of the binary number: ";
- cin >> n;
- cout << "Enter the percentage of ones in the binary number: ";
- cin >> percent;
- int ones = (n * percent) / 100;
- int zeroes = n - ones;
- int arr[n];
- for (int i = 0; i < ones; i++) {
- arr[i] = 1;
- }
- for (int i = ones; i < n; i++) {
- arr[i] = 0;
- }
- // shuffle the array
- for (int i = n-1; i >= 0; i--) {
- int j = rand() % (i+1);
- swap(arr[i], arr[j]);
- }
- cout << "Before sorting, the binary number is: ";
- for (int i = 0; i < n; i++) {
- cout << arr[i];
- }
- cout << endl;
- bubbleSort(arr, n);
- cout << "After sorting, the binary number is: ";
- for (int i = 0; i < n; i++) {
- cout << arr[i];
- }
- cout << endl;
- cout << "The number of ones in the binary number is: " << countOnes(arr[n-1]) << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement