เราได้รับค่าของประเภทข้อมูลต่างๆ เช่น เป็นจำนวนเต็ม, ทุ่น, สตริง, บูล เป็นต้น และภารกิจคือการจัดเรียงตัวแปรของประเภทข้อมูลใดๆ โดยใช้วิธีการหรือฟังก์ชันทั่วไปเพียงวิธีเดียว แล้วแสดงผลพี>
ใน C++ เราสามารถใช้ std::sort เพื่อจัดเรียงอาร์เรย์ประเภทใดก็ได้ที่มีอยู่ในไลบรารีเทมเพลตมาตรฐาน C++ (STL) โดยค่าเริ่มต้น ฟังก์ชันการเรียงลำดับจะเรียงลำดับองค์ประกอบอาร์เรย์จากน้อยไปมาก ฟังก์ชัน Sort() รับสามอาร์กิวเมนต์ -
เริ่มองค์ประกอบในรายการอาร์เรย์ เช่น จากตำแหน่งที่คุณต้องการเริ่มการจัดเรียงของคุณ
สิ้นสุดองค์ประกอบในรายการอาร์เรย์ เช่น จนถึงตำแหน่งที่คุณต้องการให้การเรียงลำดับของคุณเสร็จสิ้น
เปลี่ยนการตั้งค่าเริ่มต้นของฟังก์ชันการเรียงลำดับเป็นลำดับจากมากไปหาน้อยโดยส่งฟังก์ชันมากขึ้น () เพื่อเรียงลำดับจากมากไปหาน้อย
ตัวอย่าง
Input-: int arr[] = { 2, 1, 5, 4, 6, 3}
Output-: 1, 2, 3, 4, 5, 6
Input-: float arr[] = { 30.0, 21.1, 29.0, 45.0}
Output-: 21.1, 29.0, 30.0, 45.0
Input-: string str = {"tutorials point is best", "tutorials point", "www.tutorialspoint.com"}
Output-: tutorials point tutorials point is best www.tutorialspoint.com
แนวทางที่ใช้ในโปรแกรมด้านล่างมีดังนี้ −
- ป้อนตัวแปรของข้อมูลประเภทต่างๆ เช่น จำนวนเต็ม, ทุ่น, สตริง ฯลฯ
- ใช้ฟังก์ชัน sort() ที่จะจัดเรียงองค์ประกอบของอาร์เรย์ประเภทใดก็ได้
- พิมพ์ผลลัพธ์
อัลกอริทึม
Start
Step 1-> create template class for operating upon different type of data Template <class T>
Step 2-> Create function to display the sorted array of any data type
void print(T arr[], int size)
Loop For size_t i = 0 and i < size and ++i
print arr[i]
End
Step 3-> In main()
Declare variable for size of an array int num = 6
Create an array of type integer int arr[num] = { 10, 90, 1, 2, 3 }
Call the sort function sort(arr, arr + num)
Call the print function print(arr, num)
Create an array of type string string str[num] = { "tutorials point is best", "tutorials point", "www.tutorialspoint.com" }
Call the sort function sort(str, str + num)
Call the print function print(str, num)
Create an array of type float float float_arr[num] = { 32.0, 12.76, 10.00 }
Call the sort function sort(float_arr, float_arr+num)
Call the print function print(float_arr, num)
Stop ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
// creating variable of template class
template <class T>
void print(T arr[], int size) {
for (size_t i = 0; i < size; ++i)
cout << arr[i] << " ";
cout << endl;
}
int main() {
int num = 6;
int arr[num] = { 10, 90, 1, 2, 3 };
sort(arr, arr + num);
print(arr, num);
string str[num] = { "tutorials point is best", "tutorials point", "www.tutorialspoint.com" };
sort(str, str + num);
print(str, num);
float float_arr[num] = { 32.0, 12.76, 10.00 };
sort(float_arr, float_arr+num);
print(float_arr, num);
return 0;
} ผลลัพธ์
0 1 2 3 10 90 tutorials point tutorials point is best www.tutorialspoint.com 10 12.76 32