//+------------------------------------------------------------------+ //| sort_structure_array.mq5 | //| Copyright © 2018, Amr Ali | //| https://www.mql5.com/en/users/amrali | //+------------------------------------------------------------------+ #include "Introsort.mqh" //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ struct MyStruct { int A; int B; int C; }; //+------------------------------------------------------------------+ //| a custom comparison function Less. | //| Sort structures by A (asc), then by B (asc), then by C (asc). | //+------------------------------------------------------------------+ bool MyLessFunc(const MyStruct &x, const MyStruct &y) { //--- sort by A (asc) if(x.A < y.A) return(true); if(x.A > y.A) return(false); //--- if equal on A, sort by B (asc) if(x.B < y.B) return(true); if(x.B > y.B) return(false); //--- if equal on B, sort by C (asc) if(x.C < y.C) return(true); if(x.C > y.C) return(false); //--- all keys are equal return(false); } // Define a pointer type to custom Less function. typedef bool (*pLess)(const MyStruct &x, const MyStruct &y); //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void OnStart() { MyStruct structArray[25]; // array of structures //--- Generate random data. for(int i = 0; i < 25; i++) { structArray[i].A = rand() % 10; structArray[i].B = rand() % 10; structArray[i].C = rand() % 10; } Print("Before sort:"); ArrayPrint(structArray); //--- Sort the input array in-place using a pointer to comparison function less. Introsort(structArray, (pLess)MyLessFunc); Print("After sort:"); ArrayPrint(structArray); } //+------------------------------------------------------------------+