Advertisement
rizky_herucakra

sort an array

Jun 13th, 2013
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.02 KB | None | 0 0
  1. //
  2. //  main.cpp
  3. //  teststrcmp
  4. //
  5. //  Created by Rizky Herucakra on 6/13/13.
  6. //  Copyright (c) 2013 Rizky Herucakra. All rights reserved.
  7.  
  8. #include <iostream>
  9. #include <string>
  10.  
  11. using namespace std;
  12.  
  13. struct student
  14. {
  15.     char name[50];
  16.     float q1, q2, q3;
  17.     float ave;
  18. };
  19.  
  20.  
  21. void swap(float* a, float* b){
  22.     float tmp;
  23.     tmp = *a;
  24.     *a = *b;
  25.     *b = tmp;
  26. }
  27.  
  28.  
  29. void swap(char* a, char* b){
  30.     char buff[50];
  31.     strcpy(buff,a);
  32.     strcpy(a,b);
  33.     strcpy(b,buff);
  34. }
  35.  
  36. void swap(student* a, student* b)
  37. {
  38.     swap(&(a->q1),&(b->q1) );
  39.     swap(&(a->q2),&(b->q2) );
  40.     swap(&(a->q3),&(b->q3) );
  41.     swap(&(a->ave),&(b->ave) );
  42.     swap(a->name,b->name );
  43. }
  44.  
  45. void my_sort(student* s,int num_item){
  46.    
  47.     int n = num_item;
  48.    
  49.     do{
  50.         int newn = 0;
  51.         for (int i = 1; i <= n - 1; ++i ){
  52.             if (strcmp(s[i -1 ].name,s[i].name ) >= 0 ){
  53.                 swap(&s[i -1 ],&s[i]);
  54.                 newn = i;
  55.             }
  56.         }
  57.         n = newn;
  58.        
  59.     }while (n != 0);
  60. }
  61.  
  62. int main()
  63. {
  64.     student x[50];
  65.     int i, j, k;
  66.     char xtemp[50];
  67.    
  68.     for (i=0; i!=3; i++)
  69.     {
  70.         cout << "\n\n\tPlease enter a Student Name: ";
  71.         cin >> x[i].name;
  72.        
  73.         cout << "\n\tPlease enter his/her score for QUIZ1: ";
  74.         cin >> x[i].q1;
  75.        
  76.         cout << "\n\tPlease enter his/her score for QUIZ2: ";
  77.         cin >> x[i].q2;
  78.        
  79.         cout << "\n\tPlease enter his/her score for QUIZ3: ";
  80.         cin >> x[i].q3;
  81.        
  82.         x[i].ave = (x[i].q1+x[i].q2+x[i].q3) / 3;
  83.        
  84.         cout<<"\n\t-----------------------------------";
  85.     }
  86.    
  87.     my_sort(x,3);
  88.    
  89.     // display
  90.    
  91.     cout << "\n\n\n\tNAME\t\tQUIZ1\t\t\QUIZ2\t\tQUIZ3\t\tAVE"<<endl;
  92.    
  93.    
  94.    
  95.     for (i=0; i!=3; i++)
  96.     {
  97.         cout << "\n\t"<<x[i].name;
  98.         cout <<"\t\t"<<x[i].q1;
  99.         cout <<"\t\t"<<x[i].q2;
  100.         cout <<"\t\t"<<x[i].q3;
  101.         cout <<"\t\t"<<x[i].ave<<endl;
  102.     }
  103.    
  104.    
  105.     cin.get();
  106.     return 0;
  107. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement