/******************************************************************************
Online C++ Compiler.
Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int dlugosc_tab;
void wprowadz_dlugosc(int *tab);
void sprawdz_dlugosc(int *tab);
void insertion_sort(int *tab);
void losuj_liczby(int *tab);
void wyswietl_tab(int *tab);
/////////////////////////////////////////////////////
void swap (int* a,int* b);
/////////////////////////////////////////////////////
int main()
{
sprawdz_dlugosc(&dlugosc_tab);
printf ("\nDługość :%d\n",dlugosc_tab);
int * tab = malloc(sizeof *tab * (dlugosc_tab + 1));
if (!tab)
{
perror("malloc");
return -1;
}
srand (time(NULL));
losuj_liczby(tab);
insertion_sort(tab);
wyswietl_tab(tab);
free(tab);
}
//////////////////////////////////////////////////////////
void wprowadz_dlugosc(int *tab){
printf ("\nPodaj długość :");
scanf("%d",&(*tab));
return;
}
void sprawdz_dlugosc(int *tab) {
while (*tab <8 || *tab>22) {
printf ("\nDługość tablicy [8-22] elementów");
wprowadz_dlugosc(&*tab);
}
}
void losuj_liczby(int *tab)
{
int i;
for(i=0; i<dlugosc_tab; i++)
tab[i]= -5 + rand()%11;
return;
}
void wyswietl_tab(int *tab){
int i;
for(i=0; i<dlugosc_tab; i++)
printf (" %d,",tab[i]);
return;
}
void insertion_sort(int *tab){
int i,j,wstawiany_element;
if(dlugosc_tab<3) return;
if(tab[0]>tab[1]){swap(&tab[0],&tab[1]);}
for (i=2; i< dlugosc_tab;i++){
// # Wstaw tab[i] w posortowany ciąg tab[1 ... i-1]
wstawiany_element = tab[i];
j = i - 1;
while (j>0 && tab[j]>wstawiany_element){
tab[j + 1] = tab[j];
j--;
tab[j + 1] = wstawiany_element; }
}
for (i=0; i<dlugosc_tab-1 && tab[i]>tab[i+1];i++){
swap (&tab[i],&tab[i+1]);
}
}
//////////////////////////////////////////////////////////
void swap (int *a,int *b){
*a = *b + *a;
*b = *a - *b;
*a = *a - *b;
}