fork download
  1. //se numeste algoritmul prin insertie
  2. public class Main {
  3.  
  4. public static void InsertSort(int[] vec) {
  5.  
  6. int n = vec.length;
  7.  
  8. //{7, 6, 5, -4,3,2,-1,0};
  9. //{2, 7, 5,-4,3,2,-1,0};
  10. //{2, 5, 7,-4,3,2,-1,0};
  11. // i:1 2 3 4 5 6 7 8
  12. //aux = vec[i] = 6
  13. //j= i-1 = 0
  14. //vec[0] = 7
  15. for(int i = 1; i < n; ++i) {
  16.  
  17. int aux = vec[i];
  18.  
  19. int j = i - 1;
  20.  
  21. while(j >= 0 && vec[ j ] > aux) {
  22.  
  23. vec[j+1] = vec[j];
  24.  
  25. j-=1;
  26. }
  27. vec[j+1] = aux;
  28. }
  29. }
  30.  
  31. public static void main(String args[]) {
  32.  
  33. //declaram un vector de intregi
  34. int[] vector = {7,6,5,-4,3,2,-1,0};
  35.  
  36. //afisam pe ecran un string
  37. System.out.println("vectorul original");
  38.  
  39. //afisam vectorul pe stdout
  40. DisplayVector( vector );
  41.  
  42. InsertSort( vector );
  43.  
  44. //afisam pe ecran un string
  45. System.out.println("vectorul sortat");
  46.  
  47. //afisam inca o data vectorul sortat
  48. DisplayVector( vector );
  49. }
  50.  
  51. public static void DisplayVector(int[] vec) {
  52.  
  53. for(int value: vec) {
  54.  
  55. System.out.print(value + " ");
  56. }
  57.  
  58. System.out.println();
  59. }
  60. }
  61.  
  62. /*
  63. VECTOR: 7 8 1 5 9
  64.   i: 0 1 2 3 4
  65.   j = i - 1
  66.   <----
  67.   for(i = 1; i < lungime_VECTOR; ++i) {
  68.   temp = vec[i]
  69.   j = i - 1;//j = 0
  70.   while(j >= 0 SI vec[j] > temp) {
  71.   vec[j+1] = vec[j]
  72.   j--;
  73.   //j = j -1
  74.   }
  75.   vec[j+1] = aux;
  76.   //vec[-1+1] = aux
  77.   //vec[0] = aux
  78.   }
  79. */
Success #stdin #stdout 0.1s 55688KB
stdin
Standard input is empty
stdout
vectorul original
7 6 5 -4 3 2 -1 0 
vectorul sortat
-4 -1 0 2 3 5 6 7