homework/cpp/myfunc.cpp

45 lines
1.0 KiB
C++
Raw Permalink Normal View History

2024-05-22 17:33:42 +00:00
#include "myfunc.h"
2024-05-26 07:41:50 +00:00
2024-05-26 08:07:17 +00:00
int strncmp(const char* s1, const char* s2, int n) {
for (int i = 0; i < n; i++) {
2024-05-26 07:41:50 +00:00
if (s1[i] != s2[i]) {
return (unsigned char)s1[i] - (unsigned char)s2[i];
}
if (s1[i] == '\0' || s2[i] == '\0') {
break;
}
}
return 0;
}
2024-05-22 17:33:42 +00:00
2024-05-26 07:24:45 +00:00
bool compareWords(const char* a, int lenA, const char* b, int lenB) {
int minLen = (lenA < lenB) ? lenA : lenB;
int cmp = strncmp(a, b, minLen);
if (cmp == 0) {
return lenA < lenB;
2024-05-22 17:33:42 +00:00
}
2024-05-26 07:24:45 +00:00
return cmp < 0;
2024-05-22 17:33:42 +00:00
}
2024-05-26 07:24:45 +00:00
void bubbleSort(model arr[], int n) {
bool swapped;
for (int i = 0; i < n-1; i++) {
swapped = false;
2024-05-22 17:33:42 +00:00
2024-05-26 07:24:45 +00:00
for (int j = 0; j < n-i-1; j++) {
if (!compareWords(arr[j].ptr, arr[j].len, arr[j+1].ptr, arr[j+1].len)) {
2024-05-22 17:33:42 +00:00
2024-05-26 07:24:45 +00:00
// Zamiana miejscami
model temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
swapped = true;
2024-05-22 17:33:42 +00:00
}
}
2024-05-26 07:24:45 +00:00
if (!swapped) {
break;
}
}
}