কম্পিউটার

C++ এ বিকল্প সাজানো


একটি পূর্ণসংখ্যা অ্যারের উপাদানগুলিকে এমনভাবে সাজানো যাতে প্রথম উপাদানটি অ্যারের সর্বাধিক এবং বাছাই করা অ্যারের দ্বিতীয় উপাদানটি সর্বনিম্ন, তৃতীয়টি দ্বিতীয়টি সর্বনিম্ন, চতুর্থটি দ্বিতীয়টি সর্বাধিক। অ্যারে এবং যায়৷

ধারণাটি আরও ভালভাবে বোঝার জন্য একটি উদাহরণ নেওয়া যাক,

Input : 4 1 8 2 9 3 7
Output : 9 1 8 2 7 3 4
Explanation : The elements in a sorted way is 1 2 3 4 7 8 9. Now, 
let’s create it in the manner we wanted it i.e. alternate sorted form. 
So, the largest element of the array first i.e. 9 followed by 1 which 
is the smallest element of the array i.e. 1 next comes 8 , 2 , 7 , 3, 4.

এখন যেহেতু আমরা ধারণাটি বুঝতে পেরেছি, আমরা এই সমস্যাটির সমাধান করার জন্য একটি সমাধান বিকাশ করতে পারি। সুতরাং, একটি সম্ভাব্য সমাধান হবে অ্যারে সাজানো এবং এই সাজানো অ্যারের শেষ এবং প্রথম উপাদান প্রিন্ট করা। আসুন এই সমাধানের উপর ভিত্তি করে একটি অ্যালগরিদম তৈরি করি।

অ্যালগরিদম

Step 1 : Sort the array.
Step 2 : Create two pointers one for traversing from start and other pointer for traversing from end.
Step 3 : Print values of the pointer in alternate form and increase the value of the iterator.

উদাহরণ

#include <iostream>
using namespace std;
void alternateSort(int arr[], int n) ;
void swap(int *xp, int *yp) ;
void selectionSort(int arr[], int n) ;
int main(){
   int arr[] = { 4,1,8,2,9,3,7};
   int n = sizeof(arr)/sizeof(arr[0]);
   alternateSort(arr, n);
   return 0;
}
void alternateSort(int arr[], int n){
   selectionSort(arr, n);
   int i = 0, j = n-1;
   while (i < j) {
      cout << arr[j--] << " ";
      cout << arr[i++] << " ";
   }
   if (n % 2 != 0)
      cout << arr[i];
}
void swap(int *xp, int *yp){
   int temp = *xp;
   *xp = *yp;
   *yp = temp;
}
void selectionSort(int arr[], int n){
   int i, j, min_idx;
   for (i = 0; i < n-1; i++){
      min_idx = i;
   for (j = i+1; j < n; j++)
      if (arr[j] < arr[min_idx])
         min_idx = j;
      swap(&arr[min_idx], &arr[i]);
   }
}

আউটপুট

9 1 8 2 7 3 4

  1. C++ এ রেখার প্রতিফলন

  2. C++ এ ডায়াগোনাল ট্রাভার্স II

  3. C++ এ একটি ভেক্টর বাছাই করা

  4. C++ এ সাজানো হচ্ছে