Simple sorting function (C++/Processing/Java) -


void sort_records_by_id (int []indices, int []students_id )  {   (int k = 0; k<indices.length; k++)   {         (int j = k; j>0 && indices[j]<indices[j-1]; j--)     {      int place holder = indices[j];      indices[j] = indices [j-1];      indices[j-1] = place_holder;     }   }  }

void setup() {    int [] students_id= {10001, 20001, 12334, 14332, 99999, 10111, 20101, 12034, 10332, 99991} ;   double [] midterm_marks = {99, 67, 88, 91, 56, 90, 70, 69, 79, 59};   double [] final_marks = {89, 76, 80, 67, 99, 98, 56, 96, 90, 60};   string [] students_name= {"tim", "joe", "ali", "kim", "pam", "rob", "ben", "ted", "lee", "jim"};    print_records(students_id, midterm_marks, final_marks, students_name);   // using array of indices use indicator of order of teh records based on students id numbers     int[] indices = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};   // using insertion sort reorder indices based on students ids in ascending order   sort_records_by_id(indices, students_id);    println();    println("the students records after sorting them id numbers follows:");    print_sorted_records(indices, students_id, midterm_marks, final_marks, students_name);    // searching position of student in array of names , printing his/her records   // serarching "kim"    int position = search(students_name, "kim");    if(position == -1) {     println("search failed: " + "kim" + " not found");   }   else {     double average = calculate_student_average(midterm_marks[position], final_marks[position]);      println(students_name[position] + " found: id: " + students_id[position]             + " midterm mark: " + midterm_marks[position] + ", final mark: " + final_marks[position]             + ", term average: " + average + ", , overal grade: " + letter_grade_calculation (average));     }           // searching "sam"   position = search(students_name, "sam");      if(position == -1) {     println("search failed: " + "sam" + " not found");   }     else {     double average = calculate_student_average(midterm_marks[position], final_marks[position]);      println(students_name[position] + " found: id is: " + students_id[position]             + " midterm mark: " + midterm_marks[position] + ", final mark: " + final_marks[position]             + ", term average: " + average + ", , overal grade: " + letter_grade_calculation (average));     }       } /* -------------------------------------------------------------------- purpose of function calculate average of  numbers contained in array , return value calling  function.  function requires - array of type double  function promises -to return value of type double user  representing average of array passed  user.  --------------------------------------------------------------------- */ double calculate_class_average (double [] exam) {  int = 0;  double sum = 0;   //iterate through loop , add   //elements of array local variable  //"sum"  (i = 0; i<exam.length; i++)  {    sum+=exam[i];  }  //return value of average calculated  //by dividing sum, number of times   //loop executed, representing # of elements  return (sum/i); }  /* ----------------------------------------------------------------------- purpose of function calculate average between 2 real numbers passed user , return value calling function  function requires: -two real numbers of type double  function promises: -to return average between   2 values passed user   value of type double  ----------------------------------------------------------------------- */ double calculate_student_average(double mid_mark, double final_mark) {   //calculate , retrun average   //between 2 numbers   return (mid_mark+final_mark)/2; }  /* -------------------------------------------------------------------------- purpose of function return letter grade calling  function based on value (grade) passed function.   function requires: -a real number of type double  function promises: -to provide letter grade based on grade  provided function  -------------------------------------------------------------------------- */ char letter_grade_calculation(double student_avg) {   char ch = ' ';    //this decision structure compares value (grade)   //that passed function set of conditions   //which assign letter grade accordingly   if (student_avg>=90 && student_avg<=100)   ch = 'a';   else if (student_avg>=80 && student_avg<=89)   ch = 'b';   else if (student_avg>=70 && student_avg<=79)   ch = 'c';   else if (student_avg>=60 && student_avg<=69)   ch = 'd';   else if (student_avg>=59 && student_avg<=0)   ch = 'f';   return ch; }  /* -------------------------------------------------------------------------------------------------------------------------------------- purpose of function print out contents of 4 parallel arrays, , other information related input, including average mark , letter grade. same index in each array printed out in 1 row in console area.  content in following index printed out each array in following row. repeated until of elements in each array printed out.   function requires - 4 arrays - integer array first argument - array of type double second , third argument - array of strings fourth , final argument  function promises -to print out contents of each of these arrays in console area, printing out elements in same index  in each array 1 row, , printing out each element of 4 arrays following index in following row. repeated until of elements of each array printed in console area in fashion.  ---------------------------------------------------------------------------------------------------------------------------------------- */ void print_records(int [] students_id, double []midterm_marks, double []final_marks, string []students_name)  {   //prints header table once.    print("name \t  id \t  mid \t final\t average \t mark\n---------------------------------------------------------\n");    //loop keeps track    ( int = 0; i<midterm_marks.length; i++)   {     double avg = calculate_student_average(midterm_marks[i], final_marks[i]);     char letter = letter_grade_calculation(avg);     print(students_name[i],"\t",students_id[i],"\t",midterm_marks[i],"\t",final_marks[i],"\t",avg           ,"\t",letter, "\n");   } }  /*  */ void sort_records_by_id (int []indices, int []students_id ) {  (int k = 0; k<indices.length; k++)  {     (int j = k; j>0 && indices[j]<indices[j-1]; j--)    {     int place holder = indices[j];     indices[j] = indices [j-1];     indices[j-1] = place_holder;    }  } }  void print_sorted_records(int []index, int [] studnts_id, double []midterm_marks, double []final_marks, string []students_name)  {   for(i=0; i<index; i++)   {    int k = index[i];    print(students_name[i],"\t",students_id[i],"\t",midterm_marks[i],"\t",final_marks[i],"\t",avg           ,"\t",letter, "\n");   } } /* ----------------------------------------------------------------------------------------------------------------------- purpose of function search given array of strings particular name or sequence of letters,  , if finds name or sequence of letters, returns index number user. if equivalent entry in array not found, function returns -1 calling function.  function requires: -an array of strings search through -a string searched in array  function promises: -to return index position of target word (word searching for)in array of strings passed function. -if equivalent name or sequence of words not found in array name or sequence of letters provided user, function returns -1.  ------------------------------------------------------------------------------------------------------------------------ */ int search (string [] students_name, string target)   {   //local variable containing value or index value   //to returned calling function   int index =-1 ;    //this loop iterates through contents of array   //passed function, , compares each of elements   //to target/key word user desires search for. if match   //is found, overwrite -1 in local variable   //the index number of word, , return calling function. otherwise,   //if match not found, -1 not overwritten, , value returned   //to user @ end of loop.   (int k = 0; k<students_name.length; k++)  {   //if string @ k in array matches target word   //then assign k, counter value, representing index,    //the local variable.   if(students_name[k].equals(target) == true)   index = k;  }  return index; }    void sort_records_by_id (int []indices, int []students_id ) {  (int k = 0; k<indices.length; k++)  {     (int j = k; j>0 && indices[j]<indices[j-1]; j--)    {     int place holder = indices[j];     indices[j] = indices [j-1];     indices[j-1] = place_holder;    }  } } 

i have create function able sort array of integers, not changing , rearranging contents, changing order of integers in array of integers called indexes. so, have array series of ids such as: lets call id" [#] represents index [0]10001 12001 [2]12334 [3]14332 [4]999999 [5]10111

there corresponding array, integer values [#] index lets call arr [0]0 11 [2}2 [3]3 [4]4 [5]5 correspond indexes have in other array.

now, must change order of "arr", such elements in such order corresponds order of indexes in array id in sorted order. note, array id not changed in way.

so, can print ids console in ascending order, using loop, values of arr, , array id.

i hope able explain sufficiently. attached image clarification. enter image description here

basically, sort function, can seen above, not work should.

template<class i, class c> void sort_indexes( begin, end, c const& container ) {   using index_type = std::iterator_traits<i>::reference;   std::sort( begin, end, [&](index_type lhs, index_type rhs) {     return container[lhs]<container[rhs];   }; } 

given iterator range of indexes (begin end) , container lookup, sorts indexes.

here write generic function. takes 2 iterators begin , end. these form half-open range. works functions in <algorithm> header.

we take container. container must support lookup using indexes in our index range []. array, std::vector, std::map work here.

then punt. std::sort work. std::sort takes 3 arguments.

the first 2 iterators (which have). last comparison function object.

it must answer question "given 2 elements, smaller?". returns true if smaller 1 on left.

so lookup in container on indexes!

the rest of code template , using alias keep code generic. write structurally similar one, i being replaced int*, , container being replaced can [] on, , index_type being int, easily.

example use:

int indexes[100] = { /* blah */ }; int data[100] = { /* blah */ };  sort_indexes( indexes, indexes+100, data ); 

now in real code, i'd instead write , use order_by:

template<class f, class o=std::less<>> auto order_by( f&& f, o&& o = {}) {   return     [f = std::forward<f>(f), o = std::forward<o>(o)]     (auto&& lhs, auto&& rhs)->bool     {       return o( f(decltype(lhs)(lhs)), f(decltype(rhs)(rhs)) );     }; } 

which obscure, get:

std::sort( indexes, indexes+100, order_by( [&](int i){ return data[i]; } ) ); 

ie, work of sort_indexes gets reduced call order_by @ call site.

what order_by takes projection type t type u, generates ordering on t based off mapped-to ordering of u. want here -- order indexes values in table.


here of above generates:

void sort_indexes_to_ids( int* begin, int* end, int const* ids ) {   std::sort( begin, end, [&](int lhs, int rhs) {     return ids[lhs]<ids[rhs];   }; } 

for concrete case.


using std::sort right way solve problem. std::sort going more efficient sort you, @ level of skill, going write. if enough beat in narrow application, overhead of testing , documenting custom sort code requires justification.


Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -