Skip to content
Snippets Groups Projects
Commit 8bd5929f authored by thib's avatar thib
Browse files

pointer sort

parent 60cdc454
No related branches found
No related tags found
No related merge requests found
cc=gcc
CFLAGS=-Wextra -Wall -g -fsanitize=address -fsanitize=leak
LFLAGS= -lm
main: pointer_sort.x
./pointer_sort.x
pointer_sort.x: pointer_sort.o main.o
$(cc) -o $@ $^ $(CFLAGS) $(LFLAGS)
clean:
rm -f *.o *.x
#include "pointer_sort.h"
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
int size=8;
int* arr=random_tab(size, 0, 100);
int**ptr=sort(arr, size);
free(ptr);
free(arr);
return EXIT_SUCCESS;
}
\ No newline at end of file
#include "pointer_sort.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
void swap(int *a, int *b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
void print_array_ptr(int **arr, int size) {
for (int i = 0; i < size; i++) {
printf("%d ", *arr[i]);
}
printf("\n");
}
int* random_tab(int size,int min,int max) {
assert(max > min);
int* tab=malloc(sizeof(int)*size);
for (int i=0;i<size;i++) {
tab[i] = min+rand()%(max-min);
}
return tab;
}
int **sort(int *orig, int size) {
int **ptr = malloc(sizeof(int *) * size);
// copy addresses
for (int i = 0; i < size; i++) {
ptr[i] = &orig[i];
}
// print_array_ptr(ptr, size);
for (int j = size; j > 1; j--) {
for (int i = 0; i < j-1; i++) {
// ptr[0] est un pointeur *ptr[0] est la valeur pointée
if (*ptr[i] > *ptr[i + 1]) {
swap(ptr[i], ptr[i + 1]);
}
}
printf("[%d] ",j);
print_array_ptr(ptr, size);
}
return ptr;
}
\ No newline at end of file
#ifndef _POINTER_SORT_H_
#define _POINTER_SORT_H_
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
int** sort(int* orig,int size);
int* random_tab(int size,int min,int max);
#endif
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment